Upload FTP File With Argv - python

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.

Related

Python - transfer files in the same network using shutil

I'm moving a .txt file between two servers (Ubuntu and Windows) in the same network.
The following code doesn't show any errors but it doesn't work:
def transfer_files_task():
source_path = r"/root/airflow/testdoc"
dest_path = f"192.168.xxx.xx\Doc-Share\Logger Output"
filename = r"/test.txt"
filenamew = f"\test.txt"
shutil.copyfile(source_path + filename, dest_path + filenamew)
Change your function to this:
import os, ntpath, posixpath
def transfer_files_task():
source_file = posixpath.join("/", "root", "airflow", "testdoc", "test.txt")
dest_file = ntpath.join("192.168.xxx.xx", "Doc-Share", "Logger Output", "test.txt")
assert os.path.exists(source_file), f"{source_file} does not exists"
shutil.copyfile(source_file, dest_file)
A small explanation: leave python format your paths, it will save you from many errors. If you do not do that, you have to know how strings work, what characters should be escaped, how to format a path on linux and windows, etc.
Also, a side note about the use of r and f prefix for strings:
r stands for raw and it roughly means that you don't have to escape special characters like the backspace. Consequently, r"\tab" == "\\tab" and print(r"\tab") gives \tab while print("\tab") gives ab
f stands for format and is the new way of formatting strings in py36+. It is used as follows:
name="john"
print(f"hello {name}")
# hello john
Finally, you might want to check this post: Cannot copy file from a remote machine using shutil

getting error "not all arguments converted during string formatting - Python"

I ma using csv file to fetch some data for automatic login. In my first file, lets call it core.py, i am defining it as function.Here is my code :
import csv
def csvTodict():
dir = os.path.dirname(__file__)
filename = os.path.join(dir, './testdata/InputData.csv')
with open(filename) as f:
logins = dict(filter(None, csv.reader(f)))
return logins
and in another file, i am calling the values for username and password : Its my modules.py
from core import *
fnsignin()
def fnsignin():
try:
myDict=csvTodict()
fnLogin(myDict["Username"],myDict["Password"]
But when i run, I am getting error " not all arguments converted during string formatting". I am not sure where I am doing wrong. Please help

I Wish to Save Configuration With System IP Address

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.)

How to Retrieve a Zip Folder from FTP in Python

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'))

Download specific file from FTP using python

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.

Categories

Resources