RTLO in filename in windows - python

I wrote simple script in python
#!/usr/bin/python
from uuid import getnode as get_mac
import socket
import requests
import datetime
#import tkMessageBox as messagebox
#import Tkinter as tk
def main():
print('start')
i = datetime.datetime.now()
headers = {"Content-Type": "text/html; charset=UTF-8"}
r = requests.post("http://michulabs.pl", data={'name' : 'CI17nH', 'ip' : getIp(), 'mac' : getMac(), 'source' : 'so', 'join_date' : i})
print(r.status_code, r.reason)
print(r.text) # TEXT/HTML
print(r.status_code, r.reason) # HTTP
"""
method to read ip from computer
it will be saved in database
"""
def getIp():
ip = socket.gethostbyname(socket.gethostname())
print 'ip: ' + str(ip)
return ip
"""
method to read mac from computer
it will be saved in database
"""
def getMac():
mac = get_mac()
print 'mac: ' + str(mac)
return mac
if __name__ == "__main__":
main()
Then by py2exe generated .exe file and tried to use RTLO character in filename which made script called moc.pdf instead of pdf.com. Actually it works good with pdf.com but it doesn't after using RTLO character. Did Windows blocked that trick in filenames, or am I doing something wrong?
PS Windows didn't block that trick because it does work with other file.

Related

Using textFSM to parse multiple show commands

I'm trying to use textFSM to compile some Juniper "show" command outputs and get specific fields from them and finally printing collected info in one run.
This is my code:
import textfsm
import getpass
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
import os
def enable_netconf(remote_device):
junos_device = ConnectHandler(**remote_device)
command_2 = junos_device.send_command("show interfaces")
junos_device.disconnect()
def main():
print("Enter Device info to check:\n")
tuser = input("Enter username: ")
tpw = getpass.getpass()
with open("D:\Documents\sample3.csv", encoding='utf-8') as tf:
for line in tf:
my_ip = line.rstrip(os.linesep)
remote_device = {
'device_type': 'juniper',
'ip': my_ip,
'username': tuser,
'password': tpw,
}
enable_netconf(remote_device)
with open("D:\Documents\juniper_junos_show_interfaces.textsm", "r") as f:
template = textfsm.TextFSM(f)
result = template.ParseText(command_2)
print(result)
if __name__ == '__main__':
main()
I used Netmiko to connect to Juniper vMX device. I also download textFSM "show interfaces" temple from this link (https://github.com/networktocode/ntc-templates/blob/master/ntc_templates/templates/juniper_junos_show_interfaces.textfsm) and saved them in D:\Documents folder.
first of All I need to make the basic function of textFSM to work. in the above code I got the error saying that "command_2" variable has not been defined which as seen I defined it inside the "def enable_netconf(remote_device)".
Would you please help me on this as I'm a newbie in Python.
Thanks.
If you want to use a variable in a different def, you can use the global command. In this example, just put "global comman_2" just below def enable_netconf(remote_device):
def enable_netconf(remote_device):
global command_2
junos_device = ConnectHandler(**remote_device)
command_2 = junos_device.send_command("show interfaces")
junos_device.disconnect()

PN-RT packet malformed

I tried with that codes to comunicate with Ethernet/Profinet protocol.I found that type of codes. But when I run to the program with that line-1
And i did not get any error. My program running but when i watching the wireshark side my connection information said-2
1
sudo python3 discovery.py
2
Wireshark malformed packet PN-RT
Yes it know that is Profinet protocol, but why is the malformed ? How can i fix ?
That is my python code:
#!/usr/bin/env python
import binascii
from socket import *
from fcntl import ioctl
import struct
import fcntl, struct
value='!6s6sH'
s=socket(AF_PACKET, SOCK_RAW)
s.bind(('enp2s0',1))
class EtherPacket:
def __init__(self, dst='25:36:73:32:74:48', src='c3:82:c5:b8:c2:81', protocol=0x8892):
self.dst = dst # Destination MAC
self.src = src # Source MAC
self.protocol = protocol # Protocol Types
self.raw ="" # Raw Data
self.assemble_eth_feilds()
def assemble_eth_feilds(self):
# Assemble All Feilds Of Ether Packet
self.raw = struct.pack( \
value.encode('ascii'),\
binascii.unhexlify(self.dst.replace(":","")),\
binascii.unhexlify(self.src.replace(":","")),\
self.protocol,\
)
return self.raw
def main():
pkt = EtherPacket()
s.sendto(pkt.raw, ('enp2s0' , 0 ))
if __name__=='__main__':
main()

Use REMOTE_ADDR in an other file [duplicate]

This question already exists:
How can I display environment variable [duplicate]
Closed 8 years ago.
I code in python and I have a problem.
I have file1.py :
import os, sys, platform, getpass, tempfile
import webbrowser
import string
import json
import cgi, cgitb
def main( addr, name):
os.environ["REMOTE_ADDR"] = addr
print os.environ ["REMOTE_ADDR"]
template = open('file2.py').read()
tmpl = string.Template(template).substitute(
name = name,
addr = cgi.escape(os.environ["REMOTE_ADDR"]),
os = user_os,
user_name = user_login,
)
f = tempfile.NamedTemporaryFile(prefix='/tmp/info.html', mode='w', delete=False)
f.write(contenu)
f.close()
webbrowser.open(f.name)
if __name__ == "__main__":
addr = sys.argv[1]
name = sys.argv[2]
user_os = sys.platform
sys.argv.append(user_os)
user_login = getpass.getuser()
sys.argv.append(user_login)
main(addr, name)
in the file2.py
<form name="sD" method="get" action="${addr}">
but I have this error and I have tried to resolve it, but I don't know how can do that :(
Traceback (most recent call last):
File "./file1.py", line 47, in <module>
main(addr, name)
File "./file1.py", line 22, in main
addr = cgi.escape(os.environ["REMOTE_ADDR"])
File "/usr/lib/python2.6/UserDict.py", line 22, in __getitem__
raise KeyError(key)
KeyError: 'REMOTE_ADDR'
My problem is, I don't know how can I put a addr variable in command line and recover that IP address in an URL when I click on the OK button
Help me please :(
You have multiple problems with your code.
First, as mentioned in your previous question:
you dont (I repeat: you dont) want the IP of the client as the url for
your form's action
What, exactly, do you think this line of code is going to do?
<form name="sD" method="get" action="${addr}">
It will attempt to send the form to your end user's IP address. This will fail. This will fail because
They likely don't have a web server running
Even if they do, they likely don't have a script built to handle your form
You should be submitting the form to a page you control so that you can process it
As for your missing key error, you don't have an environment variable set. You can do this a few ways:
From outside of your python script, use this command: set REMOTE_ADDR=<value>. Replace <value> with an appropriate value.
From within your python script, use this code
Remember to import os
import os
os.environ["REMOTE_ADDR"] = "value"
Again, value should be an appropriate value.
A very simple example of what you want:
import os, sys
def main( addr, name):
os.environ["REMOTE_ADDR"] = addr
print os.environ["REMOTE_ADDR"]
if __name__ == "__main__":
addr = sys.argv[1]
name = sys.argv[2]
main(addr, name)
This outputs:
>python test.py "address" "name"
address
>python test.py "http://www.google.com" "name"
http://www.google.com
Finally, as mentioned in your previous question:
you dont (I repeat: you dont) want the IP of the client as the url for
your form's action
From your shell (i.e. command line)
$> set REMOTE_ADDR=<some url>
$> python
>>> import os
>>> print os.environ['REMOTE_ADDR']
<some url>
if you define it in the python instance it is only available to that instance
but by putting in the 'environment' before calling any module it is 'globally' available

Using Python to ssh with no modules

I'm in a pickle with writing a script that can SSH into device, run a command and parse that data out to a file. I've written this using Pyparsing and Exscript then I found out that the device I'm going to be using this on is using Python 2.4.4 and Debian 4.1.1 so the modules will not work on this. Now I am back to the drawing board trying to find out how to do this with NO modules. Anyone have any reference or point me in the right direction for this? Thank you in advance.
Here is my code:
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
import uuid
from pyparsing import *
import re
import yaml
account = read_login()
conn = SSH2()
conn.connect('172.0.0.1')
conn.login(account)
conn.execute('foobar')
data = conn.response
conn.send('exit\r')
conn.close()
###### PARSER ######
date_regex = re.compile(r'\d\d-\d\d-\d\d')
time_regex = re.compile(r'\d\d:\d\d:\d\d')
pairs = [{'category': 'General Information',
'kv': Group(Word(alphanums) + Word(alphanums))},
{'category': 'Last Reset:',
'kv': Group(Word(alphas, max=1) + Word(alphas)) + Literal(':').suppress()
+ Group(Regex(date_regex) + Regex(time_regex)
+ Optional(SkipTo(LineEnd())))
}
]
# build list of categories with associated parsing rules
categories = [Word("# ").suppress() + x['category']
+ OneOrMore(Group(x['kv']))
for x in pairs]
# account for thing you don't have specific rules for
categories.append(Word("#").suppress() + Optional(SkipTo(LineEnd())) +
Group(OneOrMore(Combine(Word(alphanums) + SkipTo(LineEnd()))))
)
# OR all the categories together
categories_ored = categories[0]
for c in categories[1:]:
categories_ored |= c
configDef = OneOrMore(categories_ored)
suppress_tokens = ["show all", "SSH>", "Active System Configuration"]
suppresses = [Literal(x).suppress() for x in suppress_tokens]
for s in suppresses:
configDef.ignore(s)
result = configDef.parseString(data)
for e in result:
print(e)
with open('/Users/MyMac/development/data.yml', 'w') as outfile:
outfile.write( yaml.dump(e))
UPDATE
I have followed the advice below and now have Pexpect installed and found a older version of Python-Pyparsing that I have also installed. So I'm on my way again to getting my scripts to work with modules. Thanks!
Looks like this is already solved, but...
As long as your SSH is configured for this host (or the host doesn't require you to log-in), you should be able to do the following.
import os
""" This will execute foobar on the remote host
and store the command output to a text file
on your machine."""
os.system("ssh 172.0.0.1 foobar > ~/data.txt")
""" Commence processing """
data = open("data.txt", mode='r')
# and so on and so on
You can also use the subprocess library, but os.system for these types of tasks is the simplest IMO.

Cannot save a BufferedReader to a file

I am trying to use http-parser and write the response to a file following the example here. This is what I am trying to do, I changed the GET request to request an image and then trying to save it to a file:
open('image.jpg', 'wb').write(p.body_file().read())
But the file has zero bytes. What am I missing here?
Complete code:
#!/usr/bin/env python
import socket
from http_parser.http import HttpStream
from http_parser.reader import SocketReader
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect(('www.linux-mag.com', 80))
s.send("GET http://www.linux-mag.com/s/i/topics/tux.jpg HTTP/1.1\r\nHost: www.linux-mag.com\r\n\r\n")
r = SocketReader(s)
p = HttpStream(r)
print p.body_file()
open('image.jpg', 'wb').write(p.body_file().read())
finally:
s.close()
if __name__ == "__main__":
main()
It turns out that I needed to sudo the script. I did sudo python <script> it works fine.

Categories