How to communicate Python with Siemens PLC using Python-snap7? - python

I am trying to communicate Python with the CPU1212C PLC (using PLCSIM), but an error always occurs.
Code:
IP = '192.168.100.100'
RACK = 0
SLOT = 1
plc = snap7.client.Client()
plc.connect(IP, RACK, SLOT)
print(plc.get_cpu_state())
No handlers could be found for logger "snap7.common"
Traceback (most recent call last):
File "C:/Python27/Teste_Snap7.py", line 8, in plc.connect(IP, RACK, SLOT)
File "C:\Python27\lib\site-packages\snap7\client.py", line 25, in f check_error(code, context="client")
File "C:\Python27\lib\site-packages\snap7\common.py", line 65, in check_error raise Snap7Exception(error)
Snap7Exception: TCP : Connection timed out
Is this a problem with Windows10?
I am using Windows10 64 bit, Python 2.7.17, Snap7 1.1.0, Python-Snap7 0.10.
I copied and pasted the snap7.dll and snap7.lib file into the System32, Python27, Python27 / site-packages / snap7 folders. And I created for each folder a path in the environment variables in an attempt to work.
I followed this tutorial: https://www.youtube.com/watch?v=BKnK4AT_WKs

It's not a problem related with Windows, in the error message you can see the problem:
Snap7Exception: TCP : Connection timed out.
Verify your physical connection to the machine and then verify the client IP.

Verify:
if PLC actually ping
if Snap7 server is enabled on your PC
if rack and slot are correct, according to your PLC.
The handbook provided with snap7 is very exhaustive, please refer to it

Verify in tia portal:
properties > Protection and security > connection mechanism > and check the "permit acess with PUT/GET.."

Related

Python & Mcpi (minecraft) - connection refused error

I use mcpi: https://github.com/AdventuresInMinecraft/AdventuresInMinecraft-Linux
Starting the local server.
After, run program:
import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()
mc.postToChat("Hello Minecraft World")
I am facing the below error:
Traceback (most recent call last):
File "/home/home/AdventuresInMinecraft/MyAdventures/HelloMinecraftWorld.py", line 2, in mc = minecraft.Minecraft.create()
File "/home/home/.local/lib/python3.6/site-packages/mcpi/minecraft.py", line 376, in create return Minecraft(Connection(address, port))
File "/home/home/.local/lib/python3.6/site-packages/mcpi/connection.py", line 17, in init self.socket.connect((address, port))
ConnectionRefusedError: [Errno 111] Connection refused
A ConnectionRefusedError means that the address + port combination was unable to be secured for this particular Minecraft server and thus raised an exception. This could be because some other application is already using the port of interest, the port is unavailable because of the OS, or a handful of other networking configuration mishaps.
But perhaps a better series of questions to ask yourself is:
What is the default address and port that minecraft.Minecraft.create() will attempt to launch / listen at?
Do I have access to that server (address + port)?
If I do have access, are there any security issues (AKA Firewall)?
This post has already addressed the root issue of your question, and I hope it gives you a good start at understanding the foundation of your problem.
Notice how their question mentions s.connect((host,port)) and your stack trace has self.socket.connect((address, port)) Looks like the same thing to me!
Some more reading:
- localhost
- check if port is in use
I encountered the same issue. I looked into the code of mcpi and found that the default port is 4711. However, a Minecraft Server's default port is 25565. All you need to do is add 2 parameters on the create() function. Code(Python):
mc = minecraft.Minecraft.create(address="127.0.0.1", port=25565)
btw change "address" in the code to the host of the server (only if you modified the "server.properties" file).
Also, ConnectionRefusedError doesn't mean that it's not secured, I believe it means that either the server is not online, it doesn't exist, or the server refused it for some reason.
EDIT:
Oops sorry I just found out that mcpi actually connects to the RaspberryJam plugin which is hosted on another IP and port. The plugin runs on port 4711. So mcpi has the right port.
So check if you have the RaspberryJam plugin installed. If not, download it from
https://www.spigotmc.org/resources/raspberryjuice.22724/
And put the .jar file inside the plugins folder in your server directory.

How to configure pysftp/paramiko connection with specific HostkeyAlgorithms - python

I need to automate transferring of a file from one server to a client's SFTP server. I've done this hundreds of time using Python's pysftp package. However, on this occasion, there's a HostkeyAlgorithm that I need to set. I've read through Paramiko's doc since pysftp seems lacking of this option entirely and is built on Paramiko. But I honestly don't know what to do (I don't get to play with networking things often). I've been sending manually through bash with the following:
sftp -o HostkeyAlgorithms=+ssh-dss user#host.com
I've tried the following in Python to no success:
import paramiko
_host='somehostname.com'
_user='thisguy'
_pass='you_get_the_idea'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
client.connect(_host, 22, _user, _pass)
This returns:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/paramiko/client.py", line 424, in connect
passphrase,
File "/usr/local/lib/python2.7/dist-packages/paramiko/client.py", line 714, in _auth
raise saved_exception
paramiko.ssh_exception.AuthenticationException: Authentication failed.
So I guess the question is where/how do I add the -o HostkeyAlgorithms=+ssh-dss when setting up my Paramiko connection?
Paramiko will use host key algorithm matching a host key that you configure for your session.
You do not specify any host key, instead you blindly accept all host keys (MissingHostKeyPolicy), what is a security flaw. You lose a protection against MITM attacks.
For a correct (and secure) approach, see:
Python - pysftp / paramiko - Verify host key using its fingerprint
Verify host key with pysftp
Though, I actually do not understand, why do you want to set "HostkeyAlgorithms", if you do not even verify the host key due to MissingHostKeyPolicy? – The "Authentication failed" error is for sure not related to host key.

Thrift TTransportException in python

I'm getting a weird error while trying to execute an RPC using thrift on python. I have found similar issues online, but none of them really apply to my situation.
Here is the error I'm getting
No handlers could be found for logger "thrift.transport.TSocket"
Traceback (most recent call last):
File "experiment.py", line 71, in <module>
transport.open()
File "/usr/local/lib/python2.7/dist-packages/thrift/transport/TTransport.py", line 152, in open
return self.__trans.open()
File "/usr/local/lib/python2.7/dist-packages/thrift/transport/TSocket.py", line 113, in open
raise TTransportException(TTransportException.NOT_OPEN, msg)
thrift.transport.TTransport.TTransportException: Could not connect to any of [('192.168.178.44', 9000)]
The following is, I believe, the code which produces it.
TECS_SERVER_IP = "192.168.178.44"
TECS_SERVER_PORT = 9000
transport = TSocket.TSocket(TECS_SERVER_IP, TECS_SERVER_PORT)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = TTSService.Client(protocol)
transport.open()
This happens whenever I try to communicate to another machine, so I tried with the ip "127.0.0.1" and it works. However, using the IP of the localhost "192.168.178.44" which should refer to the same computer also produces the error.
To me it seems like it cannot resolve IP addresses for some reason...
Any ideas on what's causing this and how to fix it?
I'm using Python 2.7.12, thrift 0.9.3 and Ubuntu 16.04, but I also got the error on Windows 10.
This is how my thrift service starts
handler = TTSHandler()
handler.__init__()
transport = TSocket.TServerSocket(host='localhost', port=9000)
processor = TTSService.Processor(handler)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
server.serve()
your server should bind to that address before client could connect to:
TSocket.TServerSocket(host='192.168.178.44', port=9000)
or use host='0.0.0.0' which means bind on all IPv4 addresses on the machine.

[Pyo/Jackd/PulseAudio]: Jack Error: Unabel to create JACK client (CromeOS/CROUTON/Precise)

Trying to get the PYO music module to work on my Chromebook (Chroot Dev) (ARM7 processor) (Precise Penguin/ubuntu 12.04)
pyo:
>>>import pyo
pyo version 0.7.7 (uses single precision)
>>>pyo.Server(audio='jack').boot()
Due to the ARM processor and Precise some small modifications to the dependencies were necessary:
1] ARM changes to /proc/cpuinfo in relation to Jackd2, error:
FATAL: cannot locate cpu MHz in /proc/cpuinfo
solution? The error changed after, but not knowledgeable enough to know if for the better.
2] xwPython3.0 not available for Precise:
solution, shouldn't be a problem as this is UI dependency correct?
And to this is where the error is now:
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jackdmp 1.9.11
Copyright 2001-2005 Paul Davis and others.
Copyright 2004-2015 Grame.
jackdmp comes with ABSOLUTELY NO WARRANTY
This is free software, and you are welcome to redistribute it
under certain conditions; see the file COPYING for details
/usr/local/bin/jackd: symbol lookup error: /usr/local/bin/jackd: undefined symbol: jackctl_driver_params_parse
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
Jack error: Unable to create JACK client
jack_client_close called with a NULL client
Server not booted.
<pyolib.server.Server object at 0x1671150>
None of the solutions to any of the error messages i managed to find on google changed this error message. (google googled other, but you don't care about my messy internet history)
pulseaudio:
>pulseaudio --start
E: [pulseaudio] main.c: Daemon startup failed.
Could this be the main problem as Precise and the ChromeOS are running sidebyside and this causes a lock on the Deamon?
>pulseaudio --kill
E: [pulseaudio] main.c: Failed to kill daemon: No such process
>sudo pulseaudio --kill
E: [pulseaudio] core-util.c: Home directory /home/USERNAME not ours.
E: [pulseaudio] main.c: Failed to kill daemon: Permission denied
sudo permission denied??? PulseAudio running in ChromeOS???
jackd:
>jack_control start
Traceback (most recent call last):
File "/usr/local/bin/jack_control", line 399, in <module>
main()
File "/usr/local/bin/jack_control", line 158, in main
bus = dbus.SessionBus()
File "/usr/lib/python2.7/dist-packages/dbus/_dbus.py", line 211, in __new__
mainloop=mainloop)
File "/usr/lib/python2.7/dist-packages/dbus/_dbus.py", line 100, in __new__
bus = BusConnection.__new__(subclass, bus_type, mainloop=mainloop)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 122, in __new__
bus = cls._new_for_bus(address_or_type, mainloop=mainloop)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NotSupported: Unable to autolaunch a dbus-daemon without a $DISPLAY for X11
This just doesn't work cause i "don't have a display" for Jackd to open up in right?
Solution 1: Connecting JACK to CRAS instead of ALSA, probably what you want unless you want to disconnect ChromeOS from audio (open link from solution 2 for more information)
Solution 2: Connecting ALSA and JACK directly to hardware by turning off CRAS

TCP port scanner written in Python using Scapy yields no response

I’m trying to make a TCP port scanner, but I’m sticking to a very simple example that I lined together from a more advanced example I found online.
I don’t get any errors.
I’m expecting the code to show me that port 80 is open since I started my Apache server on my Linux box.
Here is the code:
#!/usr/bin/python
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
ip = "127.0.0.1"
port = 80
response = sr1(IP(dst=ip)/TCP(dport=port, flags="S"),verbose=False, timeout=0.2)
if response :
if response[TCP].flags == 18 :
print "Port open"
Warning I had (but that does not show up any more):
WARNING: No route found for IPv6 destination :: (no default route?)
I read that including these two lines below would help on the error:
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
Nmap scan:
STATE SERVICE
80/tcp open http
The output is… Nothing at all.
I tried several things like changing the port to different other ports, some which I had open and some which I did not.
Any ideas as to what I did wrong?
The scapy docs mention that the loopback address is a special case
The loopback interface is a very special interface. Packets going
through it are not really assembled and dissassembled. The kernel
routes the packet to its destination while it is still stored an
internal structure. What you see with tcpdump -i lo is only a fake to
make you think everything is normal. The kernel is not aware of what
Scapy is doing behind his back, so what you see on the loopback
interface is also a fake. Except this one did not come from a local
structure. Thus the kernel will never receive it.
In order to speak to local applications, you need to build your
packets one layer upper, using a PF_INET/SOCK_RAW socket instead of a
PF_PACKET/SOCK_RAW (or its equivalent on other systems that Linux):
>>> conf.L3socket
<class __main__.L3PacketSocket at 0xb7bdf5fc>
>>> conf.L3socket=L3RawSocket
>>> sr1(IP(dst="127.0.0.1")/ICMP())
<IP version=4L ihl=5L tos=0x0 len=28 id=40953 flags= frag=0L ttl=64 proto=ICMP chksum=0xdce5 src=127.0.0.1 dst=127.0.0.1 options=''
|\>
However testing this on my OS-X machine results in the following error:
>>> conf.L3socket=L3RawSocket
>>> sr1(IP(dst="127.0.0.1")/ICMP())
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scapy/sendrecv.py", line 334, in sr1
s=conf.L3socket(filter=filter, nofilter=nofilter, iface=iface)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scapy/supersocket.py", line 64, in __init__
self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
AttributeError: 'module' object has no attribute 'AF_PACKET'
So your mileage may vary
EDIT
Apparently this is a known bug in scapy on BSD like systems (including OS-X): http://bb.secdev.org/scapy/issue/174/sniffing-loopback-in-mac-os-x-darwin

Categories