Paramiko SFTP:将内容列入文件

时间:2014-06-25 10:32:00

标签: python paramiko

尝试将列表内容写入远程文件.Below是我的代码

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn = ssh.connect(hostname='agnel-1', port=22, username='root', password='pass')
stdin, stdout, stderr = ssh.exec_command("hostname")
host = stdout.readlines()
diam_hostname = host[0].strip('\n')
gx_list = ["--hostname                                      {0}".format(diam_hostname),
           "--hostrealm                                     BNG-1.com",
           "--auth-app-id                                   16777238",
           "--verbose                                        1",
           "--port                                          3868",
           "--dictionary                                    r8-gx-standard",
           "--supported-vendor-id                           10415",
           "--supported-vendor-id                           8164",
           "--supported-vendor-id                           12645",
           "--gx-command 0",
           "--charging-rule-name                            prepaid",
           "--charg-service-id                              1",
           "--rating-grp                                    1",
           "--preemptive                                    1",
           "--disable-sctp"]
sftp = ssh.open_sftp()
try:
    f = sftp.open('{0}/Diam.gx'.format(self.inputs['minidiam_path']), 'w')
except IOError:
    print "Failed to Open the file for writing"
for s in gx_list:
    f.write(s + '\n')
f.close()

获取变量f的错误

UnboundLocalError: local variable 'f' referenced before assignment

虽然sftp打开文件但是没有任何错误。

谢谢, 阿涅尔。

1 个答案:

答案 0 :(得分:0)

您是否也看到""Failed to Open the file for writing""打印出来了?如果您的代码引发IOError,一旦处理了异常,因为您没有返回,它将执行其余的语句。例如,以下代码引发错误"NameError: name 'f' is not defined"

尝试:

    raise KeyError 

除了KeyError:

    print "Keyerror"

打印f

相关问题