免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 8042 | 回复: 12
打印 上一主题 下一主题

Python如何通过SSH会话保持 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-03-31 08:56 |只看该作者 |倒序浏览
最近想写一个关于远程执行命令的程序管理公司的服务器,想必大家有很多种方式来实现“远程执行命令”这个功能,但是如何进行会话保持呢?
比如cd到一个目录下,然后ls看到的是cd之后的目录下的信息?大家有什么好的思路来实现吗?

论坛徽章:
0
2 [报告]
发表于 2012-03-31 09:11 |只看该作者
paramiko 和crypto

论坛徽章:
33
ChinaUnix元老
日期:2015-02-02 08:55:39CU十四周年纪念徽章
日期:2019-08-20 08:30:3720周年集字徽章-周	
日期:2020-10-28 14:13:3020周年集字徽章-20	
日期:2020-10-28 14:04:3019周年集字徽章-CU
日期:2019-09-08 23:26:2519周年集字徽章-19
日期:2019-08-27 13:31:262016科比退役纪念章
日期:2022-04-24 14:33:24
3 [报告]
发表于 2012-03-31 09:18 |只看该作者
cd不好吧,直接ls

论坛徽章:
0
4 [报告]
发表于 2012-03-31 09:27 |只看该作者
回复 2# fuliangcheng

我知道有paramkio等很多模块,如何实现?
  1. #!/usr/bin/env python
  2. import paramiko

  3. hostname = 'xx.xx.xx.xx'
  4. username ='username'
  5. password = 'password'

  6. if __name__=='__main__':
  7.     paramiko.util.log_to_file('paramiko.log')
  8.     client = paramiko.SSHClient()
  9.     client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  10.     client.connect(hostname = hostname,username = username, password = password)
  11.     stdin, stdout, stderr = client.exec_command('cd /home')
  12.     stdin, stdout, stderr = client.exec_command('ls')
  13.     print stdout.read()
  14.     client.close()
复制代码
显然如上方式肯定不行,有一种如下的方式,但如何实现?
  1. transport = client.get_transport()
  2. channel = transport.open_session()
  3. channel.exec_command("tail -f /var/log/messages")
复制代码

论坛徽章:
0
5 [报告]
发表于 2012-03-31 21:48 |只看该作者
我们用的是pexpect,你可以试试。

论坛徽章:
0
6 [报告]
发表于 2012-04-01 08:29 |只看该作者
回复 5# gxrocky

pexpect可以保持SSH会话吗?
   

论坛徽章:
0
7 [报告]
发表于 2012-04-05 13:51 |只看该作者
I am using Paramiko to do some remote ssh work and could not figure out how to change directories and execute a script with the SSHClient.execute_command() function. I finally figured out that .execute_command() is basically a single session, so doing a .execute_command('cd scripts') and then executing the script with another .execute_command() reverts back to your default directory. The alternatives are to send all the commands at once separated by a ; .execute_command('cd scripts; ./myscript.sh'), or to use the .interactive() shell support. Since I only needed to fire off this script I used the first solution.

论坛徽章:
0
8 [报告]
发表于 2012-04-05 18:06 |只看该作者
直接paramiko,有常用的模块

论坛徽章:
0
9 [报告]
发表于 2012-11-29 15:45 |只看该作者
回复 8# Gray1982

我也遇到这个问题,paramiko模块怎么用哈?
   

论坛徽章:
4
水瓶座
日期:2013-09-06 12:27:30摩羯座
日期:2013-09-28 14:07:46处女座
日期:2013-10-24 14:25:01酉鸡
日期:2014-04-07 11:54:15
10 [报告]
发表于 2012-11-29 22:10 |只看该作者
只要建立了ssh会话, 对面有你的shell进程为你的服务, 你就一直保持着.

找个方便点的ssh库吧.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP