Python paramiko模組的安裝

paramiko是Python語言編寫的遵循SSH2協議,支援加密和認證方式,連接遠程伺服器執行命令或者上傳下載文件。

一、安裝paramiko

pip3 install paramiko

二、使用用戶名密碼方式遠程執行命令

import paramiko  ssh = paramiko.SSHClient()  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自動接受遠程伺服器host key  ssh.connect('127.0.0.1', 22, 'username', 'password')  # 遠程主機IP、埠、用戶名、密碼  stdin, stdout, stderr = ssh.exec_command('df -h')  # 遠程伺服器要執行的命令  for line in stdout:  	print(line)  ssh.close()  # 關閉ssh連接

三、使用用戶名密碼方式上傳或下載文件

import paramiko  t = paramiko.Transport('127.0.0.1', 22)  t.connect(username='username', password='password')  sftp = paramiko.SFTPClient.from_transport(t)  sftp.put('local_file', 'remote_folder')  t.close()
import paramiko  t = paramiko.Transport('127.0.0.1', 22)  t.connect(username='username', password='password')  sftp = paramiko.SFTPClient.from_transport(t)  sftp.get('remote_file', 'local_folder')  t.close()

四、使用ssh key方式遠程執行命令(前提遠程主機已經接受了你的公鑰)

import paramiko    private_key_path = '/home/xxx/.ssh/id_rsa'  key = paramiko.RSAKey.from_private_key_file(private_key_path)    ssh = paramiko.SSHClient()  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  ssh.connect('127.0.0.1', 22, username='username', pkey=key)  stdin, stdout, stderr = ssh.exec_command('df')  print(stdout.read())  ssh.close()

五、使用scp方式遠程執行命令

import paramiko    scp = paramiko.Transport(('127.0.0.1', 22))  scp.connect(username='username', password='password')  channel = scp.open_session()  channel.exec_command('touch hello/test.txt')  channel.close()  scp.close()

Tags: