用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 的 hostname、username、 password 、port 参数,连接服务器后,执行 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)"EOF"
ssh.close()
ret = -1
except pexpect.TIMEOUT:
print "TIMEOUT"
ssh.close()
ret = -2
return ret
到这里就结束了,大家可以参考一下,方法有很多种
标签:
ssh,远程代码
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
暂无“利用python 更新ssh 远程代码 操作远程服务器的实现代码”评论...
更新动态
2025年11月10日
2025年11月10日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]