版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
文章目录
SSH(Secure Shell)
安全外壳协议,是建立在应用层基础上的安全协议。
paramiko
安装
conda install paramiko
或 pip3 install paramiko
基本操作
import paramiko
from conf import *
# 创建ssh客户端对象
client = paramiko.SSHClient()
try:
# 首次ssh远程时会提示输入yes或no
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 远程连接
client.connect(hostname, port, username, password, timeout=20)
# 执行命令
stdin, stdout, stderr = client.exec_command('pwd')
# 获取命令执行结果,返回list
print(stdout.readlines())
except Exception as e:
print('\033[031m{}\033[0m'.format(e))
# 关闭
client.close()
- [’/root\n’]
写成类
import paramiko
from conf import *
class SSH:
def __init__(self):
self.c = paramiko.SSHClient()
self.c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.c.connect(hostname, port, username, password, timeout=20)
def __del__(self):
self.c.close()
print('\033[033m关闭SSH\033[0m')
def exec_cmd(self, command, print2=True):
stdin, stdout, stderr = self.c.exec_command(command)
if print2:
print('\033[036m{}\033[0m'.format(stdout.readlines()))
print('\033[031m{}\033[0m'.format(stderr.readlines()))
if __name__ == '__main__':
c = SSH()
c.exec_cmd('abcd') # 执行一条不存在的指令
c.exec_cmd('ls /home/hjw')
c.exec_cmd('mkdir /home/hjw/a', False) # 创建文件夹a
c.exec_cmd('ls /home/hjw')
c.exec_cmd('rmdir /home/hjw/a', False) # 删除文件夹a
c.exec_cmd('ls /home/hjw')