Paramiko模塊python
安裝:shell
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 paramiko from io import StringIO #私鑰 key = """ -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAqSvjvRx9gljKOWe1vxwXAaL3wnw/0JIWZJz35g+3c8Sd3s43 vCQh3wqqx7CmglXk4zCvX5feqlnKIPQ98dWU/2Ng+VtkBab8foPE7b+efZ5Pc7XN J3+Pjc67He2wnRjAaAJ6SjSfWLSH1wpxvOMn9tWnB0JJRFpnAW1p5Bzfy5kqRU70 Hmr8GswQgfxtdYcJ2jF8L5fEV8MqZAJ439QMs6Hz2tObTSuFd0FPVTqdSUb+r1Su aO90+vrnqGpPgIG9hB/L2PP0KDvDg+MX7lgdfD7fLd9+AJ+uI8i+4iKmllGB6rNO 4NI3Be+S5HeiOeoXAxtH/q2YKuVgRC+NGY4zbQIDAQABAoIBAH+Njitave94DxH1 dn3gKiCbxf+oO12BqMy35dpbY1EwoHAMQM3k2H0Zx+bE9Oc06F28qZ6EHemHxfXO 8p3TEoL1ZXreQ65XV+30YJl6b3/7y6BNJaBwd8bOZxuLyizJKtnBdH9a6gKyK/Ih 99wZ0lo0gbnhaujU2PGkk8DhXIRfgA4qWCAkV9cSDVBwjYk6DIzggnXzjMMsuy43 MtWN8r42tPPqeq7bhSVlZarLkgOAAap9d33Pvf8EYiYTevcoLHjPiHhFxFr8qUYw KakUv7g/aBj0npA0WjcjqvPe21IRS4LnlSRwccRCBmpQxWERj86r/KzqzHSMdr4v zVRM5UECgYEA18+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'))
示例二(上傳下載文件):ssh
import paramiko transport = 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()