I am new to Python and have just successfully completed writing and testing a script that will do the following:
Telnet into the switch.
Log in with credentials provided.
Open a file and then redirect the output of the commands to it.
Logout from the switch once done.
What I wish it to do:
I want my script to create a file in the specified directory using the IP address of the switch. Like configuration from switch with the IP address of 192.168.1.30 should be saved as 192.168.1.30.txt.
Below is a part of my script
============================
#!/usr/bin/python
import pexpect
import datetime
HOST = raw_input ("Enter the IP Address Of the switch:")
user=admin
password=admin
child = pexpect.spawn ('telnet', [HOST])
child.logfile = open("/home/tester/scripts/config.txt", "w")
==============================
As you can see if I ran the above script, the output of the commands sent via the script will be saved to the config.txt file. The contents will be erased if a different switch is telnet'd into and contents from the new switch will be saved. So, I would like the script to use the IP address entered by the user and then save the output of the commands in a different file using the IP address as the filename, so that contents of the file do not get over-written.
Any advice will be appreciated!
Thank you
Since HOST is the string "192.168.1.30", and you want the file to be named "/home/tester/scripts/192.168.1.30.txt", you can do this with simple string concatenation:
path = "/home/tester/scripts/" + HOST + ".txt"
… or, better, with string formatting:
path = "/home/tester/scripts/{}.txt".format(HOST)
Then:
child.logfile = open(path, "w")
(Of course you can also do the concatenation or format right in the middle of the open expression, if you prefer, but I think it's more readable this way.)
Related
I am using the following script to upload to SFTP. It works fine except if the filenames have non-english chars.
import pexpect
fileName = raw_input("Enter fileName")
#in the pexpect, send the following
put_string = "put {} /test/{}".format(fileName)
p.sendline(put_string)
My observation
Actual filename = 法嫁
fileName = \xe6\xb3\x95\xe5\xab\x81
put string = put \xe6\xb3\x95\xe5\xab\x81 /test/\xe6\xb3\x95\xe5\xab\x81
How can I resolve this issue ? Does SFTP support this type of PUT ? If no, how to upload non-eng chars file.
Versions
python2.7
Note - I have tried storing this as unicode, but same issue happens.
I want to edit a line in a text file in a Linux server using python. The process involves following steps
Telnet to the server (using telnetlib)
Go to the required directory
open the text file in the directory
set or unset the flag (YES or NO) of the variable in the text file based on the requirement
save the file and exit
I'm able to automate until step 2. However, I'm stuck at step 3 through 5.
I tried to mimic the steps I follow manually (using vim editor). But I'm not able to perform the 'ESC', replace and ':wq!' steps. Is there an alternative procedure to edit the file or any ways to improve upon mimicking the manual process
I have added my code here
host = input("Enter the IP address:")
port = input("Enter the port:")
tn = telnetlib.Telnet(host,port)
tn.write(b'\n')
tn.read_until(b"login:")
tn.write(b"admin" + b'\n')
tn.read_until(b"Password:")
tn.write(b"admin" + b'\n')
tn.write(b"version" + b'\n')
tn.write(b"path/to/file/" + b'\n')
# OPEN THE FILE and SET or RESET THE FLAG and CLOSE
with in_place.InPlace('filename.txt') as file:
for line in file:
line = line.replace('line_to_change', 'changed_data')
file.write(line)
print('Task executed')
I tried using the in-place library to set the flag but the programme is looking for the file in my local machine rather in the server. So it throws an error message indicating that the file is not present.
If you are able to connect to your remote server, the rest should work as follows:
with open('path/to/file','r') as fr:
data = fr.readlines() # returns list of lines
changed_data = ["changed_data\n" if line=="line_to_change\n" else line
for line in data]
with open('path/to/file','w') as fw:
for line in changed_data:
fw.write(line) # write the lines back to the back
I'm trying to retrieve a zip folder(s) from an ftp site and save them to my local machine, using python (ideally I'd like to specify where they are saved on my C:).
The code below connects to the FTP site and then *something happens in the PyScripter window that looks like random characters for about 1000 lines... but nothing actually gets downloaded to my hard drive.
Any tips?
import ftplib
import sys
def gettext(ftp, filename, outfile=None):
# fetch a text file
if outfile is None:
outfile = sys.stdout
# use a lambda to add newlines to the lines read from the server
ftp.retrlines("RETR " + filename, lambda s, w=outfile.write: w(s+"\n"))
def getbinary(ftp, filename, outfile=None):
# fetch a binary file
if outfile is None:
outfile = sys.stdout
ftp.retrbinary("RETR " + filename, outfile.write)
ftp = ftplib.FTP("FTP IP Address")
ftp.login("username", "password")
ftp.cwd("/MCPA")
#gettext(ftp, "subbdy.zip")
getbinary(ftp, "subbdy.zip")
Well, it seems that you simply forgot to open the file you want to write into.
Something like:
getbinary(ftp, "subbdy.zip", open(r'C:\Path\to\subbdy.zip', 'wb'))
quick and simple:
I have the following function, works well if i specify the file name.
import os
import ftplib
def ftpcon(self, host, port, login, pwd, path):
ftp = ftplib.FTP()
ftp.connect(host, port, 20)
try:
ftp.login(login, pwd)
ftp.cwd(path)
for files in ftp.nlst():
if files.endswith('.doc') or files.endswith('.DOC'):
ftp.retrbinary('RETR ' + files, open(file, 'wb').write)
print files
But when i use the for loop with ftp.nlst() to try to match an specific type of file, i receive the error:
coercing to Unicode: need string or buffer, type found
Since im not sure if this is the best way to do it, what could the "correct" way to download a file ?
Maybe try:
from ftplib import FTP
server = FTP("ip/serveradress")
server.login("user", "password")
server.retrlines("LIST") # Will show a FTP content list.
server.cwd("Name_Of_Folder_in_FTP_to_browse_to") # browse to folder containing your file for DL
then:
server.sendcmd("TYPE i") # ready for file transfer
server.retrbinary("RETR %s"%("FILENAME+EXT to DL"), open("DESTINATIONPATH+EXT", "wb").write) # this will transfer the selected file...to selected path/file
believe this is as correct as serves..
u can set server.set_debuglevel(0) to (1) or (2) for more detailed description while logged in to server.
I'm getting a message that "name 'ftp' is not defined"
Seems like I might have messed something else up too.
import ftplib
from ftplib import FTP
from sys import argv
import os
filename = argv
ftp = FTP(ftp.server.com)
ftp.login(username, password)
ftp.storbinary('STOR %s', open('%s', 'rb')) (filename, filename)
Your usage of ftp.server.com is illegal- you need to quote it. Python believes that "ftp" is, at that point, an identifier, which you are trying to pull the field "server" from, and finally the field "com". Since you want it to be a sever name string instead, quote it.
Additionally, you are using sys.argv incorrectly. Argv is a list of string, not a single string. Your filename should be " ".join(argv[1:]) instead, to capture the command line approximately verbatim. (argv[0] is the script itself.)
sys.argv is a list. The first item in the list is the command, the next items are the arguments given. You probably want filename = argv[1].
You will need to give values to username, password for this to work as well.