1、远程登录到linux上,使用到的模块paramiko
#远程登陆操作系统
def ssh(sys_ip,username,password,cmds):
try
#创建ssh客户端
client = paramiko.SSHClient()
#第一次ssh远程时会提示输入yes或者no
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#密码方式远程连接
client.connect(sys_ip, 22, username=username, password=password, timeout=20)
#互信方式远程连接
#key_file = paramiko.RSAKey.from_private_key_file("/root/.ssh/id_rsa")
#ssh.connect(sys_ip, 22, username=username, pkey=key_file, timeout=20)
#执行命令
stdin, stdout, stderr = ssh.exec_command(cmds[key])
#获取命令执行结果,返回的数据是一个list
result = stdout.readlines()
return result
except Exception, e:
print e
finally:
client.close()
if __name__=="__main__":
sys_ip = "192.168.0.102"
username = "root"
password = "1"
cmds = "pwd"
print ssh(sys_ip,username,password,cmds)
此处有个主意点,我遇到了,在密码登陆的时候,同样的python连接代码,放在python脚本里面执行就是报下面的错,但是将代码拷贝到python的交互模式下执行就是成功的,这个时候就是需要看下要远程的用户ssh配置是不是只支持键盘交互、密钥验证,如果是这样的话,使用密码远程登录就会报下面的错误
File "/usr/local/lib/python2.7/site-packages/paramiko/client.py", line 337, in connect
self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
File "/usr/local/lib/python2.7/site-packages/paramiko/client.py", line 528, in _auth
raise saved_exception
AuthenticationException: Authentication failed.
File "/usr/local/lib/python2.7/site-packages/paramiko/client.py", line 337, in connect
self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
File "/usr/local/lib/python2.7/site-packages/paramiko/client.py", line 528, in _auth
raise saved_exception
paramiko.SSHException: No existing session
这个是因为linux会检测远程连接有没有tty(键盘交互),脚本方式运行的时候就没有键盘交互,看网上有在connect加,allow_agent=False,look_for_keys=False这2个参数解决的,但是我的没有解决,ssh.connect('localhost',username=name,password=pw,allow_agent=False,look_for_keys=False)
2、使用ssh,需要使用到shell命令expect
首先创建一个shell脚本remotExect.sh
#!/usr/bin/expect
set timeout 2
set local_file [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set hostname [lindex $argv 3]
set remote_file [lindex $argv 4]
spawn scp $local_file $username@$hostname:$remote_file
expect {
"yes/no"#是为了捕获首次登录,要手动输入yes/no的情况
{send "yes\r";}
"password:"#为例捕获需要输入密码的行为
{send "$password\r";}
}
expect eof
然后在python中执行
import os
cpFileCmd = "./remotecp.sh 1.txt root 1 192.168.0.102 /opt/1.txt"
os.system(cpFileCmd)
到此这篇关于Python远程linux执行命令实现的文章就介绍到这了,更多相关Python远程linux执行命令内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!