通过python连接shh进行命令输入并下载指定文件
设置:端口,用户名,密码,IP
port = 22
username = 'root'
password = 'xxxxxxx'
# 测试用的交换机ip
ip = 'xxxxxxx'
链接到shh的模块
def get_msg(ip, mport, musername, mpassword, mflag):
try:
# 设置ssh连接的远程主机地址和端口
t = paramiko.Transport(ip, mport)
# 设置登录名和密码
t.connect(username=musername, password=mpassword)
# 连接成功后打开一个channel
chan = t.open_session()
# 设置会话超时时间
chan.settimeout(timeout=3600)
# 打开远程的terminal
chan.get_pty()
# 激活terminal
chan.invoke_shell()
return chan
except Exception, e:
mflag += 1
time.sleep(5)
if mflag < 3:
get_msg(ip,mport,musername,mpassword,mflag)
进行命令输入的模块
def mycmd(chan, my1flag):
try:
time.sleep(1)
# 也将xxxxx等需要输入的命令建立配置文件进行读取输入,会使得代码更为简洁
han.send("xxxxx" + '\n')
chan.send("xxxxx" + '\n')
# 这里让程序等待180秒,是因为我在处理需求的时候发现,链接到服务区,生成某些文件的时候需要等待一定的时间,此180秒仅作为个人的原因处理,也可进行循环判断,对没有生成的文件,进行再次输入命令,直到文件生成,(有时可能需要判断生成文件是否为空值)
time.sleep(180)
result = chan.recv(65535) # 得到命令返回的结果
print result
strlen = len(result) # 得到结果字符串的长度
print strlen
return result
下载文件模块
# remote_file 为目标文件
# local_file 为保存到本地的文件
# 需要注意的是,local_file不能为一个路径,而应当为一个完整的路径+文件名
def ssh_scp_get(ip, port, user, password, remote_file, local_file):
tran = paramiko.Transport(ip, port)
tran.connect(username=user, password=password)
sftp = paramiko.SFTPClient.from_transport(tran)
remote_file = remote_file
local_file = local_file
sftp.get(remote_file, local_file)
主函数
def get_others_message(msg1flag, mycmd1flag, remote_file, local_file, local_files):
# 可以允许用户输入ip/password来进行链接
# 方便建立cmd文件执行,增强变动性
ip = rinput("place input IP:")
password = input("place input password:")
port = 22
username = "root"
chan_ip_test = vpn_deploy.get_msg(ip, port, username, password, msg1flag)
vpn_deploy.mycmd(chan_ip_test, mycmd1flag)
# 使用while True 来进行下载操作,判断文件是否为空置,如果为空置,则再次下载,有时会因为服务器链接不稳定的情况,导致下载到的文件为0kb
while True:
get_files.ssh_scp_get(ip, port, username, password, remote_file, local_file)
get_files.ssh_scp_get(ip, port, username, password, remotes_file, local_files)
if not local_file and local_files:
continue
else:
break
部分操作需要有一个等待响应的时间