python paramiko远程服务器终端操作过程解析
这篇文章主要介绍了pythonparamiko远程服务器终端操作过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1.withopen写文件到本地
2.paramikoSFTPClient将文件推到salt服务端
3.paramikoSSHClient通过salt-cp将文件分发给目标服务器
1.
withopen(filePath,‘w‘)asf:#filePath文件本地路径,wwrite模式 f.write(content) returnfilePath
2.
importparamiko #1连接客户端 transport=paramiko.Transport((ssh_url,ssh_port)) transport.connect(username=ssh_user,password=ssh_pwd) #2定义与客户端交互将刚刚定义的transport当参数传递给他 sftp=paramiko.SFTPClient.from_transport(transport) #sftp.put(r‘/Users/mnt/{}‘.format(script_name),‘/mnt/{}‘.format(script_name)) sftp.put(本地路径+‘{}‘.format(文件名),目标路径+‘{}‘.format(文件名)) #5关闭连接 transport.close()
3.
#实例化一个ssh ssh=paramiko.SSHClient() #设置主机不在khost_key中也能连接 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #创建连接 ssh.connect(hostname=ssh_url,port=ssh_port,username=ssh_user,password=ssh_pwd) #执行命令,salt-cp-Lsalt_minion_hostnamelocal_url/filenametarget_url stdin,stdout,stderror=ssh.exec_command(‘salt-cp-Llocalhost.localdomain/mnt/‘+script_name+‘/mnt‘) #打印输出 print(stdout.read()) #关闭连接 ssh.close()
4.通过paramiko模块控制远程服务器cmd终端,执行git命令
importparamiko # defparmiko_con(): #实例化一个ssh ssh=paramiko.SSHClient() #设置主机不在khost_key中也能连接 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #创建连接 ssh.connect(hostname=ssh_url,port=ssh_port,username=ssh_user,password=ssh_pwd) #执行命令 #cmd=‘cd/mnt/test_pro/opsmanage/&&gitshortlog-2‘#查看最近两次的提交版本,在cmd里执行没有问题,但在函数里运行响应不出来,gitlog命令需要按q退出 #cmd=‘cd/mnt/test_pro/opsmanage/&&gitrev-listmaster‘#master分支提交记录倒叙排列 cmd=‘cd/mnt/test_pro/opsmanage/&&gitlog--since=1.weeks‘#查看近一周的提交,多条数据只有一个列表,需要进行处理,需要请移步:https://www.cnblogs.com/lutt/p/12037454.html #cmd=‘cd/mnt/test_pro/opsmanage/&&gitrev-list--all-n2‘#历史版本reverse只去两条记录(只显示commitid) #cmd=‘cd/mnt/OpsManage/&&gitbranch-a‘#查看当前所有分支,gitbranch查看当前分支 #cmd=‘cd/mnt/test_pro/opsmanage/&&gittag-l‘#查看当前所有tag stdin,stdout,stderror=ssh.exec_command(cmd) #打印输出 list2=[] ret=stdout.read().decode(‘utf-8‘) list2=ret.split(‘\n‘) print(list2) #关闭连接 ssh.close() if__name__==‘__main__‘: parmiko_con() print(‘ok‘)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。