利用python 更新ssh 远程代码 操作远程服务器的实现代码

这篇文章主要介绍了利用python 更新ssh 远程代码 操作远程服务器的实现代码,需要的朋友可以参考下

用python paramiko ssh 服务器,并pull对应目录代码的脚本

pull.py

 import paramiko import sys def sshclient_execmd(hostname, port, username, password, execmd): paramiko.util.log_to_file("paramiko.log") s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if(port==0): s.connect(hostname=hostname, username=username, password=password) else: s.connect(hostname=hostname, port=port, username=username, password=password) stdin, stdout, stderr = s.exec_command(execmd) stdin.write("Y") # Generally speaking, the first connection, need a simple interaction. print stdout.read() s.close() def main(server,project): # def main(): server_list = {'2108':{'hostname':'112.22.22.22','username':'root','password':'123456','port':2108}, '11':{'hostname':'192.168.1.11','username':'root','password':'123456','port':0} } if(server == '118'): execmd = "cd /workspace/" + project + "/ && git pull" info = os.popen(execmd).read()  # 这里是更新本地的,可以返回打印出cmd 的回显结果 print info up_list = server_list[server] hostname = up_list['hostname'] port = up_list['port'] username = up_list['username'] password = up_list['password'] execmd = "cd /workspace/" + project +  "/ && git pull" sshclient_execmd(hostname, port, username, password, execmd) if __name__ == "__main__": server = str(sys.argv[1]) project = str(sys.argv[2]) main(server,project)

上面的是更新远程 服务器上 project 目录pull 的源码。

/workspace/" + project + "/ && git pull

比如运行 `python pull.py 2108 web ` 就会 用 paramiko.SSHClient, 来连接 配置于 main 函数中的 server_list list 中的 2108 的 hostnameusernamepasswordport 参数,连接服务器后,执行 execmd 中配置好的命令。这里我用了argv 获取输入的参数,来控制要更新的项目路径。这样一个利用python ssh 远程服务器,并更新对应目录代码的脚本就完成了。

这里我配置了两个服务器,11这个服务器,没有使用到 port ,所以我做了判断,来控制连接中是否带 port 参数,不然会报错。

if(port==0):

这里注意,如果是第一次执行 需要接受 author_key 缓存,还需要注意 是否有更新权限

python使用ssh连接远程服务器,并执行命令代码

下面的代码使用pexpect生成一个ssh进程,然后连接远程服务器,并执行命令。
在使用下面程序之前,需要先通过easy_install pexpect安装pexpect程序。

 #!/usr/bin/env python # -*- coding: utf-8 -*- import pexpect def ssh_cmd(ip, passwd, cmd): ret = -1 ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd)) try: i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5) if i == 0 : ssh.sendline(passwd) elif i == 1: ssh.sendline('yes\n') ssh.expect('password: ') ssh.sendline(passwd) ssh.sendline(cmd) r = ssh.read() print r ret = 0 except pexpect.EOF: print "EOF" ssh.close() ret = -1 except pexpect.TIMEOUT: print "TIMEOUT" ssh.close() ret = -2 return ret 

到这里就结束了,大家可以参考一下,方法有很多种

以上就是利用python 更新ssh 远程代码 操作远程服务器的实现代码的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python