当前位置: 首页 > Linux

Python中的Paramiko使用示例

时间:2023-04-07 00:49:51 Linux

Paramiko:是Python用来控制liunx中文件的第三方库。可以创建文件,修改和删除文件内容等;代码示例:`#-*-coding:utf-8-*-``import``paramiko```class``ssh(``object``):``def``__init__(``self``,主机、端口、用户、密码):``self``.host``=``host``self``.port``=``port``self``.user``=``user``self``.password``=``password``self``.ssh_client``=``paramiko.SSHClient()``self``.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())``self``。ssh_client.connect(``self``.host,``self``.port,``self``.user,``self``.password)``#executecommandreturntextstring``def``sftp_exec_command(``self``,command):``arrconfiglist``=``[""]``try``:``std_in,std_out,std_err``=``self``.ssh_client.exec_command(command)``for``line``in``std_out:``arrconfiglist.append(line.strip(``"\n"``))``del``arrconfiglist[``0``]``self``.ssh_client.close()``return``arrconfiglist``except``Exceptionase:``print``(e,``"sshERROR"``)``finally``:``self``.ssh_client.close()``#执行命令不返回``def``sftp_exec_norecommand(``self``,command):``try``:``self``.ssh_client.exec_command(command)``self``.ssh_client.close()``except``Exceptionase:``print``(e,``"sshERROR"``)``finally``:``self``.ssh_client.close()``'''``在其他项目中调用,使用如下方法``importsshasssh``if__name__=='__main__':``ssh.ssh().sftp_exec_command("--命令信息--")``'''``'''``if__name__=='__main__':``rect=ssh().sftp_exec_command("")``print(rect)``'''`