如何用Python脚本自动输密码实现SSH远程建目录及SCP传输
实现Python自动执行SSH/SCP并自动输入密码
方法一:用pexpect模拟交互式输入
pexpect可以模拟命令行的交互过程,自动输入密码。先安装依赖:
pip install pexpect
自动执行SSH创建远程目录
import pexpect # 配置参数 username = "user" ip = "your_ip" password = "your_password" remote_dir = "dir/to/were/to/create/a/dir" # 构造SSH命令 ssh_cmd = f"ssh {username}@{ip} 'mkdir -p {remote_dir}'" # 启动子进程并处理交互 child = pexpect.spawn(ssh_cmd) # 匹配密码提示(不同系统提示可能不同,比如"password:"或"Password:") child.expect("password:") # 输入密码 child.sendline(password) # 等待命令执行完成 child.expect(pexpect.EOF) # 输出执行结果 print(child.before.decode())
自动执行SCP传输文件
import pexpect username = "user" ip = "your_ip" password = "your_password" local_file = "/path/to/file" remote_target = f"{username}@{ip}:path/to/target/folder/that was/created" scp_cmd = f"scp {local_file} {remote_target}" child = pexpect.spawn(scp_cmd) child.expect("password:") child.sendline(password) child.expect(pexpect.EOF) print(child.before.decode())
注意:如果要批量传输文件,可以遍历本地文件列表,循环执行上述SCP逻辑。
方法二:用paramiko原生操作SSH/SCP(推荐)
paramiko是Python的SSH协议实现库,无需调用系统命令,更适合脚本集成。先安装:
pip install paramiko
远程创建目录
import paramiko username = "user" ip = "your_ip" password = "your_password" remote_dir = "dir/to/were/to/create/a/dir" # 创建SSH客户端 ssh_client = paramiko.SSHClient() # 自动添加未知主机密钥(生产环境建议手动配置) ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接远程服务器 ssh_client.connect(hostname=ip, username=username, password=password) # 执行创建目录命令(-p确保父目录不存在时也能创建) stdin, stdout, stderr = ssh_client.exec_command(f"mkdir -p {remote_dir}") # 获取执行结果 print(stdout.read().decode()) print(stderr.read().decode()) # 关闭连接 ssh_client.close()
传输单个文件(批量可循环)
import paramiko username = "user" ip = "your_ip" password = "your_password" local_file = "/path/to/file" remote_folder = "path/to/target/folder/that was/created" # 创建SSH客户端并连接 ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=ip, username=username, password=password) # 打开SCP会话 scp = ssh_client.open_sftp() # 传输文件,远程路径需要拼接完整 remote_file_path = f"{remote_folder}/{local_file.split('/')[-1]}" scp.put(local_file, remote_file_path) # 关闭SCP和SSH连接 scp.close() ssh_client.close()
如果要批量传输,只需遍历本地文件目录的文件列表,重复执行
scp.put()即可。
内容的提问来源于stack exchange,提问作者Leah Golub
相关产品推荐
相关产品推荐

