SFTPClient类

SFTPClient类 SFTPClient类importparamikoaspk host10.1.8.128port22userrootpasswordroottry:#建立隧道tpk.Transport((host,port))#建立连接t.connect(usernameuser,passwordpassword)#客户端sftppk.SFTPClient.from_transport(t)#上传文件sftp.put(C:\\Users\\孟宇\\PyCharmMiscProject\\paramiko模块\\system.log,/root/system.log)print(成功)t.close()exceptExceptionase:print(e)成功sftp.get(/root/abc.txt,./abc.txt)print(成功)成功sftp.mkdir(/root/test)print(成功)成功sftp.rename(/root/test,/root/test_python)print(成功)成功#删除目录sftp.rmdir(/root/test_python)#删除文件sftp.remove(/root/abc.txt)print(成功)t.close()#查看文件状态print(sftp.stat(/root/system.log))#查看文件列表print(sftp.listdir(/root/))-rw-r--r--1003459720Jul09:26?[.bash_logout,.bash_profile,.bashrc,.cshrc,.tcshrc,anaconda-ks.cfg,.bash_history,.viminfo.tmp,Python-3.14.2.tgz,Python-3.14.2,.config,.cache,system.log,.viminfo]堡垒机模式下的远程命令执行importsysimportparamiko as pkimporttime# 配置信息 blhost10.1.8.128# 堡垒机 IPbluserrootblpwdroothost10.1.8.129# 业务机 IPuserrootpwdrootport22# 开始连接 pk.util.log_to_file(sshclient_system.log)sshclientpk.SSHClient()sshclient.set_missing_host_key_policy(pk.AutoAddPolicy())try: sshclient.connect(hostnameblhost,usernamebluser,passwordblpwd,timeout10)print([] 堡垒机连接成功)except Exception as e: print(f[-] 堡垒机连接失败: {e})sys.exit(1)# 创建交互式 shellchannelsshclient.invoke_shell()channel.settimeout(10)# 发送 ssh 登录业务机命令channel.send(fssh {user}{host}\n)buff# ----- 阶段1等待密码提示或 yes/no -----whileTrue: try: respchannel.recv(9999).decode(utf-8)ifnot resp:continuebuffresp print(f[DEBUG] 收到: {repr(resp)})except Exception as e: print(f[-] 接收超时/错误: {e})channel.close()sshclient.close()sys.exit(1)ifyes/noinbuff.lower(): channel.send(yes\n)buffcontinueifpassword:inbuff.lower(): print([] 检测到密码提示发送密码)break# ----- 阶段2发送密码 -----channel.send(pwd \n)buff# ----- 阶段3等待业务机 shell 提示符 -----whileTrue: try: respchannel.recv(9999).decode(utf-8)ifnot resp:continuebuffresp print(f[DEBUG] 收到: {repr(resp)})except Exception as e: print(f[-] 接收超时/错误: {e})channel.close()sshclient.close()sys.exit(1)ifpermission deniedinbuff.lower(): print([-] 业务机认证失败请检查密码)channel.close()sshclient.close()sys.exit(1)if#inbuff or$inbuff: print([] 业务机登录成功)break# ----- 阶段4执行 ifconfig 并读取输出 -----channel.send(ifconfig\n)bufftime.sleep(0.5)whileTrue: try: respchannel.recv(9999).decode(utf-8)ifnot resp:continuebuffrespif#inbuff or$inbuff:breakexcept Exception as e: print(f[-] 接收命令输出超时: {e})break# 打印输出去除最后一行提示符linesbuff.splitlines()iflines and(#inlines[-1]or$inlines[-1]): lines.pop()print(\n ifconfig 输出 \n)print(\n.join(lines))channel.close()sshclient.close()ifconfigens160:flags4163UP,BROADCAST,RUNNING,MULTICASTmtu1500inet10.1.8.129 netmask255.255.255.0 broadcast10.1.8.255 inet6 fe80::20c:29ff:feb5:6649 prefixlen64scopeid 0x20linkether 00:0c:29:b5:66:49 txqueuelen1000(Ethernet)RX packets350bytes164182(160.3KiB)RX errors0dropped0overruns0frame0TX packets372bytes40988(40.0KiB)TX errors0dropped0overruns0carrier0collisions0lo:flags73UP,LOOPBACK,RUNNINGmtu65536inet127.0.0.1 netmask255.0.0.0 inet6 ::1 prefixlen128scopeid 0x10hostloop txqueuelen1000(Local Loopback)RX packets0bytes0(0.0B)RX errors0dropped0overruns0frame0TX packets0bytes0(0.0B)TX errors0dropped0overruns0carrier0collisions0远程文件上传importparamikoimportsysimporttime# 堡垒机信息 blip10.1.8.128bluserrootblpwdroot# 业务服务器信息 hostname10.1.8.129usernamerootpasswordroot# 路径配置 tmpdir/tmpremotedir/datalocalpathC:\\Users\\孟宇\\Downloads\\Python-3.14.2.tgztmppathtmpdir/Python-3.14.2.tgzremotepathremotedir/Python-3.14.2.tgzport22PASS_PROMPTpassword:SHELL_PROMPT## 业务机提示符paramiko.util.log_to_file(syslogin.log)# ----- 阶段1上传文件到堡垒机 -----tparamiko.Transport((blip,port))t.connect(usernamebluser,passwordblpwd)sftpparamiko.SFTPClient.from_transport(t)print([] 上传本地文件到堡垒机...)sftp.put(localpath,tmppath)print([] 上传完成)sftp.close()t.close()# ----- 阶段2通过堡垒机执行 scp -----sshparamiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(hostnameblip,usernamebluser,passwordblpwd,timeout10)print([] 堡垒机 SSH 连接成功)channelssh.invoke_shell()channel.settimeout(10)time.sleep(0.5)# ---------- 2.1 先创建业务机上的目标目录 ----------mkdir_cmdfssh{username}{hostname}mkdir -p{remotedir}\nchannel.send(mkdir_cmd)print(f[] 发送创建目录命令:{mkdir_cmd.strip()})buffwhileTrue:try:respchannel.recv(9999).decode(utf-8)ifnotresp:continuebuffrespprint(f[DEBUG] mkdir 输出:{repr(resp)})exceptExceptionase:print(f[-] 接收超时:{e})channel.close()ssh.close()sys.exit(1)# 如果出现密码提示可能业务机要求密码处理ifPASS_PROMPTinbuff.lower():channel.send(password\n)buffcontinue# 如果出现提示符说明命令执行完成if#inbuffor$inbuff:print([] 目录创建完成或已存在)break# ---------- 2.2 发送 scp 命令 ----------scp_cmdfscp{tmppath}{username}{hostname}:{remotepath}\nchannel.send(scp_cmd)print(f[] 发送 scp 命令:{scp_cmd.strip()})buff# 等待密码提示如果是首次 scp 会询问whileTrue:try:respchannel.recv(9999).decode(utf-8)ifnotresp:continuebuffrespprint(f[DEBUG] scp 输出:{repr(resp)})exceptExceptionase:print(f[-] 接收超时:{e})channel.close()ssh.close()sys.exit(1)# 处理主机密钥确认ifyes/noinbuff.lower():channel.send(yes\n)buffcontinue# 检测密码提示ifPASS_PROMPTinbuff.lower():print([] 检测到密码提示发送业务机密码)channel.send(password\n)buffcontinue# 如果出现提示符传输完成if#inbuffor$inbuff:print([] scp 传输完成)break# 打印 scp 输出去除提示符行linesbuff.splitlines()iflinesand(#inlines[-1]or$inlines[-1]):lines.pop()print(\n scp 输出信息 \n)print(\n.join(lines))channel.close()ssh.close()print([] 任务完成)[]上传本地文件到堡垒机...[]上传完成[]堡垒机 SSH 连接成功[]发送创建目录命令:ssh root10.1.8.129mkdir -p /data[DEBUG]mkdir 输出:Last login: Mon Jul 20 14:05:12 2026 from 10.1.8.1\r\r\n[\x1b[91mroot\x1b[93m\x1b[92;1mxhde\x1b[0m \x1b[94m~\x1b[0m \x1b[35m14:06:02\x1b[0m]\x1b[93m#\x1b[0m []目录创建完成或已存在[]发送 scp 命令:scp/tmp/Python-3.14.2.tgz root10.1.8.129:/data/Python-3.14.2.tgz[DEBUG]scp 输出:ssh root10.1.8.129 mkdir -p /data\r\n[DEBUG]scp 输出:scp /tmp/Python-3.14.2.tgz root10.1.8.129:/data/Python-3.14.2.tgz\r\n[DEBUG]scp 输出:\rroot10.1.8.129s password: []检测到密码提示发送业务机密码[DEBUG]scp 输出:\r\n[DEBUG]scp 输出:[\x1b[91mroot\x1b[93m\x1b[92;1mxhde\x1b[0m \x1b[94m~\x1b[0m \x1b[35m14:06:03\x1b[0m]\x1b[93m#\x1b[0m []scp 传输完成scp 输出信息[]任务完成输出: ‘scp /tmp/Python-3.14.2.tgz root10.1.8.129:/data/Python-3.14.2.tgz\r\n’[DEBUG] scp 输出: \rroot10.1.8.129’s password: [] 检测到密码提示发送业务机密码[DEBUG] scp 输出: ‘\r\n’[DEBUG] scp 输出: [\x1b[91mroot\x1b[93m\x1b[92;1mxhde\x1b[0m \x1b[94m~\x1b[0m \x1b[35m14:06:03\x1b[0m]\x1b[93m#\x1b[0m ’[] scp 传输完成 scp 输出信息 [] 任务完成