#!/usr/bin/env python
import paramiko
import traceback
import socket
import time
import datetime
import logging
class SSHCommander(object):
"""class docs"""
def __init__(self, serverip, username, password):
self._username = username
self._password = password
self._host = serverip
self._port = 22
self.transport = None
self.bufsize = 65536
# Setup the logger
self.logger = logging.getLogger('MySSH')
self.logger.setLevel(logging.INFO)
fmt = '%(asctime)s SSHCommander:%(funcName)s:%(lineno)d %(message)s'
formater = logging.Formatter(fmt)
handler = logging.StreamHandler()
handler.setFormatter(formater)
self.logger.addHandler(handler)
self.info = self.logger.info
self.debug = self.logger.debug
self.error = self.logger.error
self.connect()
def __del__(self):
if self.transport is not None:
self.transport.close()
self.transport = None
def logout(self):
if not self.isClosed():
self.client.close()
self.client = None
def connect(self):
'''Try to connect, maybe again.'''
self.client = paramiko.SSHClient()
self.client.load_system_host_k
Python 实现交互式执行命令
最新推荐文章于 2024-08-29 17:26:27 发布
该博客介绍了如何使用Python的paramiko库实现SSH连接,并执行交互式命令。通过创建SSHCommander类,实现了连接、断开、执行命令和SFTP文件传输等功能,包括错误处理和日志记录。
摘要由CSDN通过智能技术生成
paramiko提供了SSH 客户端的接口,让大家在写脚本的时候可以remote到远端的机器上运行命令;有时候在运行某些命令的时候我们需要输入一些值,接着才往下跑,下面是一个简单的脚本来解决这个动态输入的问题: