如何在python脚本中将文本文件中的IP地址分配给主机名

时间:2015-06-30 19:52:59

标签: python variables login hostname ftplib

我能够从文本中检索并分配用户名和密码,并将其传递给ftplib以获取" ftp.login"

我如何对文本文件中的IP地址做同样的事情,我想传递给" ftplib.FTP(" 0.0.0.0")"而不是(0.0.0.0)想用" ftplib.FTP(主机名)替换它?

这是脚本:

#!/usr/bin/env python

import ftplib
import os
import sys
import paramiko
import datetime
import pickle
import ftplib as ftp
import socket




login = {}
with open('hostname1.txt', 'r') as g:
   for line in g:
       hostname = line.strip()
       login[hostname] = hostname


credentials = {}
with open('Usernames.txt', 'r') as f:
    for line in f:
        username, password = line.strip().split(':')
        credentials[username] = password

try:
        try:
            print "Connecting to 192.168.189.130"
            ftp = ftplib.FTP(hostname)
            ftp.login(username, password)
            ftp.cwd('dir1')
            ftp.retrlines('LIST')
#           ftp.get()

        except ftplib.all_errors as e:
            print(e)
except ftp.login as s:
    print (s)

1 个答案:

答案 0 :(得分:0)

感谢“Praneeth”快速回复!

回答了我自己的问题。

这有效!

我的简单错误...没有删除带有ftplib.FTP(主机名)行的()中的双引号......“

请使用它很棒!

#!/usr/bin/env python

import ftplib
import os
import sys
import paramiko
import datetime
import pickle
import ftplib as ftp
import socket




login = {}
with open('hostname1.txt', 'r') as g:
   for line in g:
       hostname = line.strip()
       login[hostname] = hostname


credentials = {}
with open('Usernames.txt', 'r') as f:
    for line in f:
        username, password = line.strip().split(':')
        credentials[username] = password

try:
        try:
            print "Connecting to 0.0.0.0"
            ftp = ftplib.FTP(hostname)
            ftp.login(username, password)
            ftp.cwd('dir1')
            ftp.retrlines('LIST')
#           ftp.get()

        except ftplib.all_errors as e:
            print(e)
except ftp.login as s:
    print (s)