使用Python Paramiko向Linux服务器发送iperf -s命令遇异常求助
问题原因
你遇到的核心问题是:iperf -s 默认是前台阻塞运行的服务端程序,它会持续监听网络连接,不会主动退出。而 paramiko 的 stdout.readlines() 会一直等待命令执行完成并输出所有内容,导致 Python 程序卡在这一步,直到你手动杀死 iperf 进程,命令才会终止,readlines() 才会拿到输出并退出。
解决方案
要解决这个问题,需要让 iperf -s 后台运行,避免阻塞 Python 程序。可以通过命令重定向和后台执行符号实现,同时可以将输出写入日志文件方便后续查看。
修改后的代码示例
remote_server = "172.22.94.171" client = paramiko.client.SSHClient() username = "useruser" password = "password" client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(remote_server, port=22, username=username, password=password) # 让iperf后台运行,将标准输出和错误输出重定向到日志文件 command = 'sudo iperf -s > /tmp/iperf_server.log 2>&1 &' stdin, stdout, stderr = client.exec_command(command, get_pty=True) stdin.write(password + '\n') stdin.flush() # 确保密码输入被提交给sudo # 检查命令执行状态 exit_status = stdout.channel.recv_exit_status() if exit_status == 0: print("iperf服务端已成功启动") # 可选:读取iperf的启动日志 _, log_out, _ = client.exec_command('cat /tmp/iperf_server.log') print("iperf启动日志:", log_out.readlines()) else: print("iperf启动失败,错误信息:", stderr.readlines()) client.close()
关键说明
- 后台运行命令:
&符号让iperf -s在后台执行,命令会立即返回,不会阻塞 Python 程序。 - 输出重定向:
> /tmp/iperf_server.log 2>&1将 iperf 的标准输出和错误输出都写入日志文件,避免无输出导致的异常,同时方便后续排查问题。 - stdin.flush():确保密码输入被立即提交给 sudo,避免因缓冲区未刷新导致的 sudo 等待输入问题。
内容的提问来源于stack exchange,提问作者Кирилл Химов
相关产品推荐
相关产品推荐

