python paramiko使用的一点心得

近期,需要实现一些功能,通过python去控制远程linux,这里就接触到了paramiko模块
这里有挺多小技巧和大家一起分享下
1.通过SSH去连接远程服务器
由于如果linux host/user等不对,都会引起连接时候的异常,所以我么可以捕获下异常

    def connectLinux(self,remoteDict:dict) -> bool:
        #checkDict valid
        for ii in range(len(self.linuxKeyPara)):
            if self.linuxKeyPara[ii] not in remoteDict:
                return False
        self.SSHClient = paramiko.SSHClient()
        self.SSHClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            self.SSHClient.connect(hostname=remoteDict["host"], port=remoteDict["port"], username=remoteDict["username"], password=remoteDict["pwd"])  # 通过SSH连接到linux
            self.ssh_transp = self.SSHClient.get_transport()
            return True
        except BaseException as e:
            print(e)
            return False

2.通过SSH去控制Linux时,经常遇到以下异常,通过查找资料以及实际测试发现,这个其实是由于发送的命令还没有执行完成导致的问题,可采用如下的code来规避
Paramiko “TypeError: ‘NoneType’ object is not callable” at the end of a script that execute command on the server

   def execCmd(self,cmd:str,cmdTime=1) -> (str,str):
        if self.SSHClient is not None:
            chan = self.ssh_transp.open_session()
            chan.exec_command(cmd)
            outdata, errdata = "", ""
        	sleeptime = 0.001
        	cnt = 0
        	while 1:
	            if cnt >= 800: #防止长时间无响应
	                break
	            while chan.recv_ready():
	                outdata += chan.recv(1000).decode()
	            while chan.recv_stderr_ready():
	                errdata += chan.recv_stderr(1000).decode()
	            if chan.exit_status_ready():
	                break
	            time.sleep(sleeptime)
	            cnt += 1
        return outdata, errdata


最主要的是第二个坑,调试了很久
不过我的主要任务是连接上,控制好之后关于p4 cmd的操作,这里项目相关,不贴出来,有需要的交流的可以留言

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值