写一段python代码,实现ssh登录
时间: 2023-03-15 21:55:45 浏览: 75
要使用Python实现SSH登录,需要使用paramiko库。下面是一个简单的Python代码示例:
```python
import paramiko
# 建立SSH连接
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', port=22, username='username', password='password')
# 执行远程命令
stdin, stdout, stderr = ssh.exec_command('ls')
print(stdout.readlines())
# 关闭SSH连接
ssh.close()
```
在上面的代码中,我们首先建立了一个SSH连接,使用给定的主机名、端口号、用户名和密码。然后,我们可以使用`exec_command`方法执行任何远程命令。在这个例子中,我们执行了`ls`命令,然后打印出结果。最后,我们关闭SSH连接。
相关问题
写一段python代码,使用多线程建立多个SSH连接
以下是使用多线程建立多个SSH连接的Python代码:import threading
import paramikodef ssh_connect(ip, username, password, command):
client = paramiko.SSHClient()
# 设置允许连接不在know_hosts文件中的主机
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
client.connect(ip, username=username, password=password)
# 执行命令
stdin, stdout, stderr = client.exec_command(command)
# 获取命令结果
result = stdout.read()
# 关闭连接
client.close() return resultif __name__ == '__main__':
# 连接的主机列表
ip_list = ['192.168.1.1', '192.168.1.2', '192.168.1.3']
# 用户名
username = 'root'
# 密码
password = '123456'
# 要执行的命令
command = 'ls'
# thread_num为线程数量
thread_num = 3
# 保存线程
threads = [] # 创建线程
for i in range(thread_num):
ip = ip_list[i]
t = threading.Thread(target=ssh_connect, args=(ip, username, password, command))
threads.append(t) # 启动线程
for t in threads:
t.start()
# 等待线程结束
for t in threads:
t.join()
PythonPython写一段文件传输的代码
以下是一个简单的 Python 文件传输代码,可以将本地文件传输到远程服务器:
```
import paramiko
# 连接远程服务器
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('remote_server_ip', port=22, username='username', password='password')
# 将本地文件传输到远程服务器
sftp = ssh.open_sftp()
local_file_path = '/path/to/local/file'
remote_file_path = '/path/to/remote/file'
sftp.put(local_file_path, remote_file_path)
# 关闭连接
sftp.close()
ssh.close()
```
需要注意的是,这个代码需要 paramiko 库的支持,可以使用 pip 进行安装:
```
pip install paramiko
```