Paramiko模块

安装:

pip3 install paramiko

示例:

import paramiko# 创建ssh对象ssh = paramiko.SSHClient()# 允许连接不在know_host文件中的主机ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 连接服务器ssh.connect(hostname='39.107.24.78',port=22,username='root',password='123456')# 执行命令stdin,stdout,stderr = ssh.exec_command('hostname')# 获取命令结果result = stdout.read()# 关闭连接ssh.close()print(result.decode('utf-8'))### 使用秘钥连接# 获取私钥private_key = paramiko.RSAKey.from_private_key_file(r'/Users/liuguixiang/.ssh/id_rsa')ssh.connect(hostname='39.107.24.78',port=22,username='root',pkey=private_key)

import paramikofrom io import StringIO#私钥key = """-----BEGIN RSA PRIVATE KEY-----MIIEowIBAAKCAQEAqSvjvRx9gljKOWe1vxwXAaL3wnw/0JIWZJz35g+3c8Sd3s43vCQh4wqqx7CmglXk4zCvX5feqlnKIPQ98dWU/2Ng+VtkBab8foPE7b+efZ5Pc7XNJ3+Pjc67He2wnRjAaAJ6SjSfWLSH1wpxvOMn9tWnB0JJRFpnAW1p5Bzfy5kqRU70Hmr8GswQgfxtdYcJ2jF8L5fEV8MqZAJ439QMs6Hz2tObTSuFd0FPVTqdSUb+r1SuaO90+vrnqGpPgIG9hB/L2PP0KDvDg+MX7lgdfD7fLd9+AJ+uI8i+4iKmllGB6rNO4NI3Be+S5HeiOeoXAxtH/q2YKuVgRC+NGY4zbQIDAQABAoIBAH+Njitave94DxH1dn3gKiCbxf+oO12BqMy35dpbY1EwoHAMQM3k2H0Zx+bE9Oc06F28qZ6EHemHxfXO8p3TEoL1ZXreQ65XV+30YJl6b3/7y6BNJaBwd8bOZxuLyizJKtnBdH9a6gKyK/Ih99wZ0lo0gbnhaujU2PGkk8DhXIRfgA4qWCAkV9cSDVBwjYk6DIzggnXzjMMsuy43MtWN8r42tPPqeq7bhSVlZarLkgOAAap9d33Pvf8EYiYTevcoLHjPiHhFxFr8qUYwKakUv7g/aBj0npA0WjcjqvPe21IRS4LnlSRwccRCBmpQxWERj86r/KzqzHSMdr4vzVRM5UECgYEA18+pP4uVgbgwawsJ2LsuBha/Hyc30G4h9Fe+t6yP22OAwQoyoQwe-----END RSA PRIVATE KEY-----"""# 创建ssh对象ssh = paramiko.SSHClient()# 允许连接不在know_host文件中的主机ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 获取私钥private_key = paramiko.RSAKey(file_obj=StringIO(key))# 连接服务器ssh.connect(hostname='39.107.24.79',port=22,username='root',pkey=private_key)# 执行命令stdin,stdout,stderr = ssh.exec_command('hostname')# 获取命令结果result = stdout.read()# 关闭连接ssh.close()print(result.decode('utf-8'))

示例二(上传下载文件):

import paramikotransport = paramiko.Transport(('39.107.24.78',22))transport.connect(username='root',password='123456')sftp = paramiko.SFTPClient.from_transport(transport)# 上传sftp.put('a.txt','/data/a.txt')# 下载sftp.get('/data/a.txt','b.txt')transport.close()