python wget 卡住_python – Paramiko在执行大型wget命令时挂起
嗨,我在执行一个通过Ubuntu 10服务器执行100mb文件的wget的命令时遇到问题.除此之外,较短的命令工作正常.下面的类包含我如何使用paramiko和我克服这个问题的不同尝试(请参阅不同的run或exec方法).在exec_cmd的情况下,执行挂起在这一行:
out = self.in_buffer.read(nbytes, self.timeout)
来自paramiko的channel.py模块的recv方法.
使用Mac中的普通ssh实用程序,相同的wget命令在shell中完美运行.
"""
Management of SSH connections
"""
import logging
import os
import paramiko
import socket
import time
import StringIO
class SSHClient():
def __init__(self):
self._ssh_client = paramiko.SSHClient()
self._ssh_client.load_system_host_keys()
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.time_out = 300
self.wait = 5
def connect(self, hostname, user, pkey):
retry = self.time_out
self.hostname = hostname
logging.info("connecting to:%s user:%s key:%s" % (hostname, user, pkey))
while retry > 0:
try:
self._ssh_client.connect(hostname,
username=user,
key_filename=os.path.expanduser(pkey),
timeout=self.time_out)
return
except socket.error, (value,message):
if value == 61 or value == 111:
logging.warning('SSH Connection refused, will retry in 5 seconds')
time.sleep(self.wait)
retry -= self.wait
else:
raise
except paramiko.BadHostKeyException:
logging.warning("%s has an entry in ~/.ssh/known_hosts and it doesn't match" % self.server.hostname)
logging.warning('Edit that file to remove the entry and then try again')
retry = 0
except EOFError:
logging.warning('Unexpected Error from SSH Connection, retry in 5 seconds')
time.sleep(self.wait)
retry -= self.wait
logging.error('Could not establish SSH connection')
def exists(self, path):
status = self.run('[ -a %s ] || echo "FALSE"' % path)
if status[1].startswith('FALSE'):
return 0
return 1
def shell(self):
"""
Start an interactive shell session on the remote host.
"""
channel = self._ssh_client.invoke_shell()
interactive_shell(channel)
def run(self, command):
"""
Execute a command on the remote host. Return a tuple containing
an integer status and a string containing all output from the command.
"""
logging.info('running:%s on %s' % (command, self.hostname))
log_fp = StringIO.StringIO()
status = 0
try:
t = self._ssh_client.exec_command(command)
except paramiko.SSHException:
logging.error("Error executing command: " + command)
status = 1
log_fp.write(t[1].read())
log_fp.write(t[2].read())
t[0].close()
t[1].close()
t[2].close()
logging.info('output: %s' % log_fp.getvalue())
return (status, log_fp.getvalue())
def run_pty(self, command):
"""
Execute a command on the remote host with a pseudo-terminal.
Returns a string containing the output of the command.
"""
logging.info('running:%s on %s' % (command, self.hostname))
channel = self._ssh_client.get_transport().open_session()
channel.get_pty()
status = 0
try:
channel.exec_command(command)
except:
logging.error("Error executing command: " + command)
status = 1
return status, channel.recv(1024)
def close(self):
transport = self._ssh_client.get_transport()
transport.close()
def run_remote(self, cmd, check_exit_status=True, verbose=True, use_sudo=False):
logging.info('running:%s on %s' % (cmd, self.hostname))
ssh = self._ssh_client
chan = ssh.get_transport().open_session()
stdin = chan.makefile('wb')
stdout = chan.makefile('rb')
stderr = chan.makefile_stderr('rb')
processed_cmd = cmd
if use_sudo:
processed_cmd = 'sudo -S bash -c "%s"' % cmd.replace('"', '\\"')
chan.exec_command(processed_cmd)
result = {
'stdout': [],
'stderr': [],
}
exit_status = chan.recv_exit_status()
result['exit_status'] = exit_status
def print_output():
for line in stdout:
result['stdout'].append(line)
logging.info(line)
for line in stderr:
result['stderr'].append(line)
logging.info(line)
if verbose:
print processed_cmd
print_output()
return exit_status,result
def exec_cmd(self, cmd):
import select
ssh = self._ssh_client
channel = ssh.get_transport().open_session()
END = "CMD_EPILOGqwkjidksjk58754dskhjdksjKDSL"
cmd += ";echo " + END
logging.info('running:%s on %s' % (cmd, self.hostname))
channel.exec_command(cmd)
out = ""
buf = ""
while END not in buf:
rl, wl, xl = select.select([channel],[],[],0.0)
if len(rl) > 0:
# Must be stdout
buf = channel.recv(1024)
logging.info(buf)
out += buf
return 0, out
解决方法:
我遇到了同样的问题,当我在远程ssh客户端上运行shell脚本时,我的python脚本挂起,在400Mb文件上执行了wget命令.
我发现在wget命令中添加超时可以解决问题.
原来我有:
现在用这个:
它就像一个魅力!
希望能帮助到你.
标签:python,linux,ssh,paramiko
python wget 卡住_python – Paramiko在执行大型wget命令时挂起相关推荐
- Python os.system(command),这样执行的command命令,和主程序是异步的吗?
Python os.system(command),这样执行的command命令,和主程序是异步的吗? 是同步执行的. 尚未执行完成的情况下,下面的程序不会继续操作.看下面的例子即可: >> ...
- 在 ubuntu 20.04 LTS 上安装 ROS2 执行 rosdep update 命令时出现的问题的解决办法
在 ubuntu 20.04 LTS 上安装 ROS2 执行 rosdep update 命令时出现的问题的解决办法 1.sudo rosdep init 在执行 sudo rosdep init 命 ...
- ceph-deploy install时,远端节点在执行apt-get update命令时失败
2019独角兽企业重金招聘Python工程师标准>>> 环境 OS:Ubuntu 16.04 背景 使用ceph-deploy部署Ceph集群,调用ceph-deploy insta ...
- 执行git commit命令时提示Please tell me who you are.
问题:执行git commit命令时提示"Please tell me who you are." 猜测是太久没使用了,它需要验证是谁在用, 解决方案 在git界面输入以下指令. ...
- python subprocess使用_python利用subprocess执行交互命令
已经知道,os.system可以方便的利用python代码执行一些像ping.ipconfig之类的系统命令,但却只能得到命令执行是否成功,不能获得命令成功执行后的结果,像下面这样: 1 >&g ...
- python3 os.system 异步执行_《sentos python教程》 Python os.system(command),这样执行的command命令,和主程序是异步的吗?...
如何学习python的os模块 就那么几个长用的方法属性,还要怎么学 python os模块怎么使用 常用方法: 1. os.name--判断正在实用的平Windows 返回 'nt'; Linux ...
- python网络监控程序_Python之利用psutil写一个命令行网速实时监控小程序
前言: psutil是一个非常强大的跨平台库,这篇文章只使用了psutil的一小小部分的功能. psutil简介: psutil(进程和系统实用程序)是一个跨平台库,用于 在Python中检索有关正在 ...
- 每次执行java命令 都要source_解决每次执行Java等命令时都要重新source /etc/profile后才能执行,否则找不到命令...
linux mint 我们通常将环境变量设置在/etc/profile这个文件中,这个文件是全局的. /etc/profile:在登录时,操作系 统定制用户环境时使用的第一个文件 ,此文件为系统的每个 ...
- Node.js 在命令行下执行Console.log()命令时,第二行会打印undefined的原因
转载:http://blog.csdn.net/chy555chy/article 问题描述:在命令行下执行Console.log()命令后,第一行会以 "正常的白字" 输出log ...
最新文章
- 如何用matlab读取npz文件,Python Numpy中数据的常用的保存与读取方法
- 在线绘图|差异分析——在线做时序分析
- OSChina 周三乱弹 —— 一起 High High High!
- ADO.Net练习1
- Xamarin图表开发基础教程(10)OxyPlot框架支持的图表类型
- 如何快速找出找出两个数组中的_找出JavaScript中两个数组之间的差异
- 数据结构——最短路径之Dijkstra算法(与最小生成树的prime算法很像,建议一起看)
- 输入一个数,判断他是不是质数
- vue-day03-vue组件化开发
- 【Kafka】Kafka 配置 SASL_SSL jks鉴权验证方式
- java实现Execl中的STDEVP函数
- Cookie和Session的区别和联系
- iOS学习之WebView的使用
- Android 仿京东分类功能实现
- FaShop-开源拖拽式小程序搭建平台
- iOS 9 Spotlight搜索 OC版
- LC振荡电路的工作原理
- 2019 ICPC 徐州网络赛
- Java做彩虹进度条,Android自定义控件-彩虹条进度条
- 实测榛子云短信平台短信接收速度
热门文章
- 【Kafka】Kafka集群扩展以及重新分布分区-分区重新分配
- xStream:Security framework of XStream not initialized, XStream is probably vulnerable.
- Maven右边栏红色,omitted for duplicate 而且Failed to execute goal on project xxx-service: Could not resolve
- 源码:Hadoop-2.7.4 启动过程中执行start-all.sh开始
- 云计算实战系列十六(SQL II)
- php变量在html调用函数调用,PHP_如何在html标记中调用的函数里传递对象,最近使用jquery结合Ajax开发一个 - phpStudy...
- 关于零拷贝技术,你了解多少?
- 面试官常考的 21 条 Linux 命令
- lisp语言100以内勾股数_三个视频搞定:函数的最值、对勾函数、分式函数性质与图像、分段函数最值...
- phpexcel删除行_使用PHPExcel删除行