Remote execution of commands based on user name and password connection
Import Paramiko
# Create an SSH object
1 ssh = Paramiko. Sshclient ()
# Allow connections to hosts that are not in the Know_hosts file
1 ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
# Connection Server
1 ssh.connect (hostname='123.56.157.199', port=22022, username=' Root', password='asbsdf. ')
# Execute Command
while True:cmd =input (" >>: " ). Strip () stdin, stdout, stderr = Ssh.exec_command (cmd) /span># Get command result result = Stdout.read () print (Result.decode ( " utf-8 " # close connection Ssh.close ()
Login based on key
1 import Paramiko 2 3 Private_key = Paramiko. Rsakey.from_private_key_file (R ' c:\\id_rsa ")
# Create an SSH object
SSH = Paramiko. Sshclient ()
# Allow connections to hosts that are not in the Know_hosts file
Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
# Connection Server
1 ssh.connect (hostname='123.56.157.199', port=22, username=' Root', Pkey=private_key)
# Execute Command
stdin, stdout, stderr = Ssh.exec_command (' df ')
# Get command results
result = stdout.read ()
Print(Result.decode ('utf-8'))
# Close Connection
Ssh.close ()
#上传下载
1 ImportParamiko2 3Transport = Paramiko. Transport (('123.56.157.199', 22022))4Transport.connect (username='Root', password='HLH199300.')5 6SFTP =Paramiko. Sftpclient.from_transport (transport)7 #uploading location.py to the server/tmp/test.py8Sftp.put (R'C:\\id_rsa','/tmp/test.rsa')9 #download Remove_path to local Local_pathTen #sftp.get (' Remove_path ', ' Local_path ') OneTransport.close ()
The learning journey of python---paramiko module