Paramiko module can realize the SSH function of Linux
1. Implement a simple SSH, log on to another server to execute a command
Import Paramiko #导入模块, provided the PIP is installed
SSH = Paramiko. Sshclient ()
Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) #允许将信任的主机自动加入到host_allow list, this method must be placed in front of the Connect method
Ssh.connect (hostname= ' 192.168.200.102 ', port=22, username= ' root ', password= ' 666666 ') #连接服务器
stdin, stdout, stderr = Ssh.exec_command (' hostname ') #stdin标准输入, stdout standard output, STDERR standard error
Res,err = Stdout.read (), Stderr.read ()
result = Res If res else err #三元远算
Print (Result.decode (). Strip ())
Ssh.close ()
2, the above example is the implementation of the server execution command, the next example is to pass the file, that is, to implement the SCP function
Import Paramiko
Transport = Paramiko. Transport (("192.168.200.102", 22))
Transport.connect (username= "root", password= "666666")
SFTP = Paramiko. Sftpclient.from_transport (transport)
Sftp.put ("/etc/passwd", "/tmp/passwd.bak")
Sftp.get ("/tmp/passwd.bak", "/tmp/passwd.bak")
Transport.close ()
Python Paramiko module