python 通过公网ssh跳板机进入内网ssh主机执行命令
#coding:utf-8 import paramiko import threading import requests import json import time def wr(time,content): name="10.25"+str(time).replace(':','').replace(' ','-')+'.txt' f=open('./log/'+name,'w+',encoding='utf-8') f.write(content) f.close() def ding_send(text): headers={ "Content-Type": "application/json" } message={ "msgtype": "text", "text": { "content":text } } a=requests.post(url="https://oapi.dingtalk.com/robot/send?access_token=",data=json.dumps(message),headers=headers) print(a.text) def ssh2(ip,username,port,passwd,cmd): try: output='' ssh = paramiko.SSHClient() now=time.strftime("%Y-%m-%d----%H%M%S") ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,passwd,timeout=5) for m in cmd: stdin, stdout, stderr = ssh.exec_command(m) out = stdout.readlines() outlen=len(out) i=1 for o in out: output=output+o+'\n' # i=i+1 # time.sleep(5) url=wr(now,output) ssh.close() #print(len(output)) #print(output) ding_send('10.25====='+now+'\n'+url) #for i in range(0,int(len(output)/19000)+1): # ding_send(now+'\n'+str(i+1)+"/"+str(int(len(output)/19000 )+1)+'\n'+output[i*19000:(i+1)*19000]) # time.sleep(1) #print(output) except : ding_send("server err!") print('err') if __name__=='__main__': cmd = ["sshpass -p '密码' ssh root@内网ip free -g","sshpass -p '密码' ssh root@内网ip ps aux --sort=-rss"] username = "root" passwd = "密码" threads = [] ip='跳板机ip' port=跳板机端口 a=threading.Thread(target=ssh2,args=(ip,username,port,passwd,cmd)) a.start()
跳板机上sshpass的安装:
yum install sshpass