1, remote login to Linux, the use of the module Paramiko
#远程登陆操作系统def SSH (SYS_IP,USERNAME,PASSWORD,CMDS): Try #创建ssh客户端 CLI ent = Paramiko. Sshclient () #第一次ssh远程时会提示输入yes或者no client.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) #密码方式远程连接 Client.connect (sys_ip, Username=username, Password=password, timeout=20) #互信方式远程连接 #key_file = Paramiko. Rsakey.from_private_key_file ("/root/.ssh/id_rsa") #ssh. Connect (sys_ip, Username=username, Pkey=key_file, Timeou T=20) #执行命令 stdin, stdout, stderr = Ssh.exec_command (Cmds[key]) #获取命令执行结果, the returned data is a list result = Stdout.readlines () return result except Exception, E:print e finally:client.close () if __nam e__== "__main__": sys_ip = "192.168.0.102" username = "root" password = "1" cmds = "pwd" Print ssh (sys_ip,us ERNAME,PASSWORD,CMDS)
Here's an idea, I met, when the password login, the same Python connection code, put in a Python script to execute is to report the following error, but copy the code into Python interactive mode execution is successful, This is the time to look at the remote user SSH configuration is not only support keyboard interaction, key authentication, if so, using password remote login will report the following error
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_exceptionauthenticationexception: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_exceptionparamiko. Sshexception:no existing session
This is because Linux will detect the remote connection there is no TTY (keyboard interaction), script mode runs without keyboard interaction, see the Internet in Connect Plus, allow_agent=false,look_for_keys=false these 2 parameters resolved, But mine is not resolved, ssh.connect (' localhost ', username=name,password=pw,allow_agent=false,look_for_keys=false)
2, use SSH, need to use to shell command expect
First create a shell script remotexect.sh
#!/usr/bin/expectset timeout 2set 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 [email protected] $h Ostname: $remote _fileexpect {"yes/no" #是为了捕获首次登录, to manually enter yes/no case {send "yes\r";} " Password: "#为例捕获需要输入密码的行为 {send" $password \ r ";}} Expect EOF
And then execute it in Python.
Import Oscpfilecmd = "./remotecp.sh 1.txt Root 1 192.168.0.102/opt/1.txt" Os.system (cpfilecmd)
Python Remote Linux Execution command