Connect from a cisco device to http server on debian - python

I'm trying to communicate with a http server which is running on debian strech from a brand new out of the box cisco device. Now, the so called zero touch configuration is no problem:
The Switch gets an IP address and such via DHCP and a link to where to fetch it's initial configuration.
The switch gets its basic configuration such as user credentials etc.
The problem rises when I try to search through a database on the server from the switch. In this database some variables are stored. Depending the serialnumber of the switch, it should receive a specific hostname, Mgmt address etc.
On those new switches there is a python module integrated so I ran some tests. I tried to fetch the serial number and got them whithout any problems. The moment I tried to write the serial number on a txt file on the server I got this error
Traceback (most recent call last): File "", line 1, in
IOError: [Errno 2] No such file or directory:
'http://10.232.152.19:80/temp.txt'
Code so far:
from cli import cli
def get_serial():
serial = cli("show version | include System Serial\n")
serial = (serial.split()[-1])
f = open ("http://10.232.152.19:80/temp.txt", "a")
f.write(serial)
f.close
get_serial()

The problem you are facing is because you are trying to open a file from the network. You need to download the file first in you system and then open it. You should use urllib to fetch the file and then open it. then save it and again push it back.
import urllib
txt = urllib.urlopen(target_url).read()

Related

SMTP_HELO returns timeout when running email address validation

Using library py3-validate-email-1.0.5 (more here) to check if email address is valid, including SMTP check, I wasn't able to make it through check_smtp step, because I get following error:
Python script
from validate_email import validate_email
from validate_email import validate_email_or_fail
from csv import DictReader
# iterate over each line by column name
with open('email-list.csv', 'r') as read_obj:
csv_dict_reader = DictReader(read_obj, delimiter=';')
for row in csv_dict_reader:
i = 1
while i < 21:
header_name = 'Email'+str(i)
if validate_email_or_fail(
email_address=row[header_name],
check_format=True,
check_blacklist=True,
check_dns=True,
dns_timeout=10,
check_smtp=True,
smtp_timeout=5,
smtp_helo_host='emailsrv.domain.com',
smtp_from_address='email#domain.com',
smtp_skip_tls=False,
smtp_tls_context=None,
smtp_debug=False):
print('Email ' + row[header_name] + ' is valid.')
else:
print('Email ' + row[header_name] + ' is invalid.')
i += 1
Error:
Traceback (most recent call last):
File "//./main.py", line 13, in <module>
if validate_email_or_fail(
File "/usr/local/lib/python3.9/site-packages/validate_email/validate_email.py", line 59, in validate_email_or_fail
return smtp_check(
File "/usr/local/lib/python3.9/site-packages/validate_email/smtp_check.py", line 229, in smtp_check
return smtp_checker.check(hosts=mx_records)
File "/usr/local/lib/python3.9/site-packages/validate_email/smtp_check.py", line 197, in check
raise SMTPTemporaryError(error_messages=self.__temporary_errors)
validate_email.exceptions.SMTPTemporaryError: Temporary error in email address verification:
mx.server.com: 451 timed out (in reply to 'connect')
I figured there is problem with my DNS settings (probably), so I dockerized the script and run it on AWS EC2, where I have used elastic IP, attached it to the EC2 instance where docker container is running, I also setup reverse DNS for domain emailsrv.domain.com with this elastic IP. Tried to run the script, no change.
Then I added MX record pointing to the emailsrv.domain.com, but still no change. The DNS records are setup properly, because I have checked it with multiple DNS tools available.
Since the library doesn't require to actually use my email address login details, I wonder what can be the problem? Just to be sure, the email address used in the script doesn't exist, since I don't have smtp server setup on that instance, obviously.
Any ideas?
Reason behind this was closed port on AWS EC2 instance. Opening the port in security group is not enough, you must send a request to AWS so they remove the restriction on port 25.
When they did that, works flawlessly.

receiveing "550 data channel timed out" while using python storbinary

I am trying to upload files from a UNIX server to a windows server using python FTP_TLS. Here is my code:
from ftplib import FTP_TLS
ftps = FTP_TLS('server')
ftps.connect(port=myport)
ftps.login('user', 'password')
ftps.prot_p()
ftps.retrlines('LIST')
remote_path = "MYremotePath"
ftps.cwd(remote_path)
ftps.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))
myfile.close()
ftps.close()
I can connect to the server successfully and receive the list of files, but I am not able able to upload the file and after some time I receive the following error:
ftplib.error_perm: 550 Data channel timed out due to not meeting the minimum bandwidth requirement.
I should mention that I am able to upload files on the same server using perl FTPSSL library. The problem happens only in python.
Does anyone have any idea about how to resolve this issue?
Thanks

Send parameters via url (urllib) to another machine

I am developing a python script that opens a file, gets the data inside this file and send it via url to a Django server.
import os
import urllib
stockPath = "/Desktop/myfile.txt"
f = open(stockPath)
mydata = f.readline()
print (mydata)
params = urllib.urlencode({'mydata': mydata})
f = urllib.urlopen("http://127.0.0.1:8000/home/%s" % params)
print (f.geturl())
This is working perfect in local. Now for some reason I have to start the Django server in another machine.
Of course I install python and django in that new machine and I start Django server. So everything is running ok.
This new machine is in the same network as mine, so I can reach it, the ping works.
The problem is that if I change the ip address for the new one, it doesn't work:
f = urllib.urlopen("http://10.32.2.94:8000/home/%s" % params)
I would be gratefull if sombebody could help me.
You need to listen on all interfaces, for example:
./manage.py runserver 0.0.0.0:8000
By default it only listens locally.

FTP'd Text file using Python 3 is empty

I am trying to FTP a file from a windows box running python 3.3 to a linux box running Ubuntu 12.04.
I have been able to FTP the file, but the file on the remote server is always empty even though the local file has about 8k in it. Its a small text file.
I have tried a few suggestions from both Google and the SE network. All the different tests are commented out. Those have failed with various errors and/or similar results as the uncommented one. (0 byte file)
I also read in the txt file to ensure I was FTPing the right file.
Code is below. Any help would be greatly appreciated:
filename = 'Music.txt'
#write data to file
file = open('Music.txt', 'w+')
for music in musicList:
file.write(music+'\n')
file.close()
localfile = open(filename, 'r')
#print(localfile)
#for line in localfile:
# print(line)
#ftp file to webserver for consumption
ftp = FTP(host) # connect to host webdev (local)
ftp.login(username, password)
print(ftp.getwelcome())
ftp.cwd('projects/home/musicCat/data')
ftp.retrbinary("RETR Music.txt", localfile.write)
#ftp.storlines("STOR Music.txt", open('Music.txt'))
#ftp.storbinary("STOR Music.txt", localfile.write)
#ftp.storbinary("STOR Music.txt", file(file, "rb"))
#ftp.storbinary('STOR' + localfile.name, open(file.name, 'wb').write)
#ftp.storlines("STOR Music.txt", open(localfile, 'r'))
#ftp.storlines('STOR Music.txt', file)
print(ftp.retrlines('LIST'))
ftp.quit()
Interpreter Output:
220 (vsFTPd 2.3.5)
-rw-r--r-- 1 1000 1000 0 Dec 27 21:14 Music.txt
226 Directory send OK.
>>>
BUMP: Anyone have any ideas? I have yet to be able to successfully transfer the file via ftp. I'm debating about using python 2.7 and paramiko.
I'm sure you're looking for a cross-platform pure python approach, but sometimes it's easiest to just use python to execute an external utility via subprocess.call()
http://docs.python.org/3.3/library/subprocess.html
I had similar issues establishing a SSH tunnel from Windows, and really did not want to switch to 2.7 to use paramiko. I ended up just calling plink.exe from my script.
For ftp on Windows, you can use the built-in utility ftp
Transfers files to and from a computer running an FTP server service
(sometimes called a daemon). Ftp can be used interactively.
FTP [-v] [-d] [-i] [-n] [-g] [-s:filename] [-a] [-A] [-x:sendbuffer] [-r:recvbuffer] [-b:asyncbuffers] [-w:windowsize] [host]
-v Suppresses display of remote server responses.
-n Suppresses auto-login upon initial connection.
-i Turns off interactive prompting during multiple file
transfers.
-d Enables debugging.
-g Disables filename globbing (see GLOB command).
-s:filename Specifies a text file containing FTP commands; the
commands will automatically run after FTP starts.
-a Use any local interface when binding data connection.
-A login as anonymous.
-x:send sockbuf Overrides the default SO_SNDBUF size of 8192.
-r:recv sockbuf Overrides the default SO_RCVBUF size of 8192.
-b:async count Overrides the default async count of 3
-w:windowsize Overrides the default transfer buffer size of 65535.
host Specifies the host name or IP address of the remote
host to connect to.
Notes:
- mget and mput commands take y/n/q for yes/no/quit.
- Use Control-C to abort commands.

Interfacing with TUN\TAP for MAC OSX (Lion) using Python

I found the following tun\tap example program and can not get it to work:
http://www.secdev.org/projects/tuntap_udp/files/tunproxy.py
I have modified the following lines:
f = os.open("/dev/tun0", os.O_RDWR)
ifs = ioctl(f, TUNSETIFF, struct.pack("16sH", "toto%d", TUNMODE))
ifname = ifs[:16].strip("\x00")
The first line was modified to reflect the real location of the driver. It was originally
f = os.open("/dev/net/tun", os.O_RDWR)
Upon running I get the following error:
sudo ./tuntap.py -s 9000
Password:
Traceback (most recent call last):
File "./tuntap.py", line 65, in <module>
ifs = ioctl(f, TUNSETIFF, struct.pack("16sH", "toto%d", TUNMODE))
IOError: [Errno 25] Inappropriate ioctl for device
I am using the latest tun\tap drivers installed from http://tuntaposx.sourceforge.net/download.xhtml
The OSX tun/tap driver seems to work a bit different. The Linux example dynamically allocates a tun interface, which does not work in OSX, at least not in the same way.
I stripped the code to create a basic example of how tun can be used on OSX using a self-selected tun device, printing each packet to the console. I added Scapy as a dependency for pretty printing, but you can replace it by a raw packet dump if you want:
import os, sys
from select import select
from scapy.all import IP
f = os.open("/dev/tun12", os.O_RDWR)
try:
while 1:
r = select([f],[],[])[0][0]
if r == f:
packet = os.read(f, 4000)
# print len(packet), packet
ip = IP(packet)
ip.show()
except KeyboardInterrupt:
print "Stopped by user."
You will either have to run this as root, or do a sudo chown your_username /dev/tun12 to be allowed to open the device.
To configure it as a point-to-point interface, type:
$ sudo ifconfig tun12 10.12.0.2 10.12.0.1
Note that the tun12 interface will only be available while /dev/tun12 is open, i.e. while the program is running. If you interrupt the program, your tun interface will disappear, and you will need to configure it again next time you run the program.
If you now ping your endpoint, your packets will be printed to the console:
$ ping 10.12.0.1
Ping itself will print request timeouts, because there is no tunnel endpoint responding to your ping requests.
so about the 'No such file or directory' error when doing:
f = os.open("/dev/tun12", os.O_RDWR)
this worked for me:
brew install Caskroom/cask/tuntap

Categories

Resources