python_ssh连接

首先下载paramiko
pip install paramiko
查看并启动ssh服务
service ssh status

添加用户:
useradd -d /home/zet zet
passwd zet
赋予ssh权限
vi /etc/ssh/sshd_config
添加
AllowUsers:zet


客户端代码

#-*- coding:utf8 -*-
 
import threading
import paramiko
import subprocess
 
def ssh_command(ip, user, passwd, command, port = 22):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())    #设置自动添加和保存目标ssh服务器的ssh密钥
    client.connect(ip, port, username=user, password=passwd)  #连接
    ssh_session = client.get_transport().open_session() #打开会话
    if ssh_session.active:
        ssh_session.send(command)   #发送command这个字符串,并不是执行命令
        print ssh_session.recv(1024)    #返回命令执行结果(1024个字符)
        while True:
            command = ssh_session.recv(1024)    #从ssh服务器获取命令
            try:
                cmd_output = subprocess.check_output(command, shell=True)
                ssh_session.send(cmd_output)
            except Exception, e:
                ssh_session.send(str(e))
        client.close()
    return
 
ssh_command('127.0.0.1', 'zet', 'zet', 'clientconnected',8001)

 

 

服务端代码

#-*- coding:utf8 -*-
 
import socket
import paramiko
import threading
import sys
 
# 使用 Paramiko示例文件的密钥
#host_key = paramiko.RSAKey(filename='test_rsa.key')
host_key = paramiko.RSAKey(filename='/root/.ssh/id_rsa')
 
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 == 'qing') and (password == 'qing'):
            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)    #TCP socket
    #这里value设置为1,表示将SO_REUSEADDR标记为TRUE,操作系统会在服务器socket被关闭或服务器进程终止后马上释放该服务器的端口,否则操作系统会保留几分钟该端口。
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('127.0.0.1', 8001))   #绑定ip和端口
    sock.listen(100)    #最大连接数为100
    print '[+] Listening for connection ...'
    client, addr = sock.accept()
except Exception, e:
    print '[-] Listen failed: ' + str(e)
    sys.exit(1)
print '[+] Got a connection!'
 
try:
    bhSession = paramiko.Transport(client)
    bhSession.add_server_key(host_key)
    server = Server()
    try:
        bhSession.start_server(server=server)
    except paramiko.SSHException, x:
        print '[-] SSH negotiation failed'
    chan = bhSession.accept(20) #设置超时值为20
    print '[+] Authenticated!'
    print chan.recv(1024)
    chan.send("Welcome to bh_ssh")
    while True:
        try:
            command = raw_input("Enter command:").strip("\n")   #strip移除字符串头尾指定的字符(默认为空格),这里是换行
            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, e:
    print '[-] Caught exception: ' + str(e)
    try:
        bhSession.close()
    except:
        pass
    sys.exit(1)

 

服务端必须创建bh_sshserver.py文件:

利用ssh-keygen -t rsa 命令创建密钥文件/root/.ssh/id_rsa,

 

posted @ 2018-10-17 22:03  时光凉&春衫薄  阅读(2161)  评论(0编辑  收藏  举报