Reputation: 328
I wrote a python script below to make a SFTP connection to a server by giving server credentials like IP,USERNAME,PASSWORD from another text file. eventhough i am successful I don't think it is the best method to do it,Please suggest some suggestions so that i can improve the code
text file format:
127.0.0.1,jack,password
MY CODE:
import os
import pysftp
import socket
from stat import S_IMODE, S_ISDIR, S_ISREG
import time
import os.path
import shutil
import fileinput
import lock
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
f = open("text.txt", "r")
for line in f:
words = line.split(',')
IP=words[0]
myUsername=words[1]
myPassword=words[2]
print(IP)
print(myUsername)
print(myPassword)
with pysftp.Connection(host=IP, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
print("connection successful")
Upvotes: 0
Views: 300
Reputation: 1150
Since your file format looks like csv you could use the csv module.
import csv
with open("text.txt", "r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
print(row)
row
is a list with ip,username,pass
Example:
Textfile:
127.0.0.1,jack,password
127.0.0.1,jack2,password2
127.0.0.1,jack3,password3
Output:
> ['127.0.0.1', 'jack', 'password']
> ['127.0.0.1', 'jack2', 'password2']
> ['127.0.0.1', 'jack3', 'password3']
Be carefull a password could contain a ,
in the string.
Anyway storing passwords in a text file isn't a good solution.
Upvotes: 1