Paramiko module describes remote connection to SSH
Connection based on username and password
1 Import Paramiko2 3 # Create an SSH object4SSH =Paramiko. Sshclient ()5 # Allow connections to hosts that are not in the Know_hosts file6 Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())7 # Connection Server8Ssh.connect (hostname='x.x.x.x', port= A, username='Xiaoli, password='123456')9 Ten # Execute Command Onestdin, stdout, stderr = Ssh.exec_command ('DF') A # Get command results -result =Stdout.read () - the # Close Connection -Ssh.close ()
View Code
Encapsulation-based transport connections
1 Import Paramiko2 3#1Create a Transport object4Transport = Paramiko. Transport (('x.x.x.x', A))5Transport.connect (username='Xiaoli', password='123456')6 7SSH =Paramiko. Sshclient ()8Ssh._transport =Transport9 Tenstdin, stdout, stderr = Ssh.exec_command ('DF') One print stdout.read () A -Transport.close ()
View Code
Connection based on public key
1 It 's like a password, but it's just where the secret becomes the private key.2 3 Import Paramiko4 5 #私钥路径6Private_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa')7 8 # Create an SSH object9SSH =Paramiko. Sshclient ()Ten # Allow connections to hosts that are not in the Know_hosts file One Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) A # Connection Server -Ssh.connect (hostname='x.x.x.x, port=22, Username='Xiaoli, key=Private_key) - the # Execute Command -stdin, stdout, stderr = Ssh.exec_command ('DF') - # Get command results -result =Stdout.read () + - # Close Connection +Ssh.close ()
View Code
Encapsulation-based transport connections
1 same as the top.2 3 Import Paramiko4 5Private_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa')6 7Transport = Paramiko. Transport (('x.x.x.x', A))8Transport.connect (username='Xiaoli', pkey=Private_key)9 TenSSH =Paramiko. Sshclient () OneSsh._transport =Transport A -stdin, stdout, stderr = Ssh.exec_command ('DF') - theTransport.close ()
View Code
Python Tour 10 "tenth chapter" Paramiko module