Python ssh client

使用Python实现ssh client功能

依赖模块:paramiko
安装方式:pip3 install paramiko 或者 sudo apt-get install python-paramiko

具体实现的代码:

#导入paramiko模块
import paramiko
#导入ssh client模块
from paramiko.client import SSHClient, AutoAddPolicy
#导入异常处理
from paramiko import AuthenticationException
from paramiko.ssh_exception import NoValidConnectionsError

#创建SshClient 类
class SshClient():
	#初始化
    def __init__(self):
        self.ssh_client = SSHClient()
	#登录
    def ssh_login(self, host_ip, username, password):
        try:
        	#允许连接不在known_hosts文件中的主机,及自动输入yes
            self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
            self.ssh_client.connect(host_ip, port=22, username=username, password=password)
        except AuthenticationException:
            logging.warning('username or password error')
            return 1001
        except NovalidConnectionsError:
            logging.warning('connect time out')
            return 1002
        except:
            print("Unexpected error:", sys.exc_info()[0])
            return 1003
        return 1000

    def execute_some_command(self, command):
    	#执行命令,打印结果
        stdin, stdout, stderr = self.ssh_client.exec_command(command)
        print(stdout.read().decode())

    def ssh_logout(self):
    	#注销链接
        self.ssh_client.close()


if __name__=="__main__":
    command = "cd"
    ssh = SshClient()
    if ssh.ssh_login(host_ip="127.0.0.1", username="zhang", password="123456") == 1000:
        ssh.execute_some_command(command)
        ssh.ssh_logout()
        print("success ssh connent")
    else:
        print("error connect to host ")

参考文章:

  1. Python—实现ssh客户端(连接远程服务器)
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值