用 python 写一个ssh
时间: 2024-05-10 10:15:18 浏览: 6
要用 Python 写 SSH 客户端,可以使用 Paramiko 库。以下是一个简单的例子,可以使用它连接到远程服务器并执行命令:
```python
import paramiko
# 创建 SSH 客户端
ssh = paramiko.SSHClient()
# 允许连接不在 known_hosts 列表中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接到远程服务器
ssh.connect(hostname='example.com', port=22, username='username', password='password')
# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls -l')
# 输出命令结果
print(stdout.read().decode())
# 关闭连接
ssh.close()
```
在上面的例子中,我们使用 Paramiko 库创建了一个 SSH 客户端对象,并设置了连接到远程服务器的相关参数,然后使用 `exec_command` 方法执行了一个命令,并输出了命令的结果。最后,我们关闭了 SSH 连接。
相关问题
用Python写一个ssh函数
好的,我可以帮您解答这个问题。首先,需要安装Paramiko模块,用于Python操作ssh。
下面是一个简单的ssh函数的示例:
```
import paramiko
def ssh(ip, username, password, command):
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip, username=username, password=password)
stdin, stdout, stderr = ssh_client.exec_command(command)
output = stdout.readlines()
ssh_client.close()
return output
```
在上面的函数中,我们使用Paramiko模块创建了一个SSHClient对象,并设置了缺失主机键的策略。然后使用connect()方法登录到远程服务器,并使用exec_command()方法执行命令。最后,函数返回命令输出结果。
示例使用方法:
```
output = ssh('192.168.1.1', 'username', 'password', 'ls -l')
print(output)
```
上面命令执行后,会输出远程服务器上当前目录的文件列表。
希望这个示例对你有帮助。
python写一个ssh巡检程序
以下是一个简单的Python SSH巡检程序示例,使用paramiko库实现SSH连接和远程命令执行:
```python
import paramiko
# 连接SSH远程主机函数
def ssh_connect(host, port, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, port=port, username=username, password=password)
return ssh
# 执行远程命令函数
def ssh_command(ssh, command):
stdin, stdout, stderr = ssh.exec_command(command)
result = stdout.read().decode()
if result:
return result
else:
return stderr.read().decode()
# 巡检函数,执行多个命令并输出结果
def check_server(host, port, username, password):
ssh = ssh_connect(host, port, username, password)
print('=================巡检开始=================')
print(f'主机名:{host}')
print(f'当前时间:{ssh_command(ssh, "date")}')
print(f'系统版本:{ssh_command(ssh, "cat /etc/issue")}')
print(f'CPU使用率:{ssh_command(ssh, "top -bn1 | grep Cpu | awk \'NR==1{print $2}\'")}')
print(f'内存使用率:{ssh_command(ssh, "free | grep Mem | awk \'{print $3/$2 * 100.0}\'")}%')
print('=================巡检结束=================')
ssh.close()
# 调用巡检函数
check_server('192.168.1.100', 22, 'root', 'password')
```
以上程序中,`ssh_connect()`函数用于连接SSH远程主机,`ssh_command()`函数用于执行远程命令并返回结果,`check_server()`函数用于执行多个命令并输出结果。可以根据实际需求修改命令内容和输出格式。