To execute a command remotely with a password
[email protected] script]# cat daramiko_ssh.py #!/usr/bin/env python#_*_coding:utf-8 _*___author__ = ' gaogd ' Import Paramikoimport sys,oshost = Sys.argv[1]user = ' root ' password = ' ddfasdsasda2015 ' cmd = Sys.argv[2]s = Paramiko. Sshclient () #绑定实例s. Load_system_host_keys () #加载本机KONW_HOST主机文件s. Set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) S.connect (host,22,user,password,timeout=5) #连接远程主机stdin, Stdout,stderr = S.exec_command (cmd) #执行命令 Cmd_result = Stdout.read (), Stderr.read () #读取命令结果for line in Cmd_result:print line,s.close ()
To execute a command remotely using key
[[Email protected] script]# cat daramiko_ssh_key.py #!/usr/bin/env python#_*_ coding:utf-8 _*___author__ = ' Gaogd ' import paramikoimport sys,oshost = sys.argv[1]port = 22username = ' root ' pkey_file = '/root/.ssh/id_rsa ' key = paramiko. Rsakey.from_private_key_file (Pkey_file) Cmd = sys.argv[2]s = paramiko. Sshclient () #绑定实例s. Load_system_host_keys () #加载本机KONW_ Host Hosts file S.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) S.connect (host,port,username,pkey=key,timeout=5) Stdin,stdout,stderr = s.exec_command (cmd) #执行命令cmd_result = stdout.read (), Stderr.read () #读取命令结果for line in cmd_result: print line,s.close () [[email protected] script]#
Upload Download file
[email protected] script]# cat daramiko_sftp.py #!/usr/bin/pythonimport os,sysimport paramikohost = ' 192.168.10.11 ' user = ' root ' password = ' [email protected] ' s = Paramiko. Sshclient () S.load_system_host_keys () S.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) T = Paramiko. Transport ((host,22)) T.connect (username=user,password=password) #pkey_file = '/home/alex/.ssh/id_rsa ' #key = Paramiko . Rsakey.from_private_key_file (Pkey_file) #t. Connect (username=username,pkey=key) sftp = Paramiko. Sftpclient.from_transport (t) sftp.get ('/root/.ssh/known_hosts ', '/tmp/known_hosts1 ') sftp.put ('/python/script/ daramiko_ssh_key.py ', '/tmp/paramiko1.py ') s.close () [[email protected] script]#
This article from "Struggle Bar" blog, declined reprint!
Python implementation ssh remote execute command upload download file