Python script crashes when I run opc.write () using OpenOpc - python

I am making a python program to write variables to an opc DA server.
I have the connection and others, but when trying to write values ​​for a variable, the program does not respond and a windows error message appears saying:
My code:
import OpenOPC
import sys
opc = OpenOPC.client()
servers = opc.servers()
idServer = int(2)
print('connecting to opc server:', servers[idServer])
opc.connect(servers[idServer])
print('connection okey:', servers[idServer])
write = opc.write(('variableName', 1))
print('write:', write)
input('> ')
Does anyone know why the program crashes when it reaches that part? Thanks a lot

Related

RTD client in Python

my goal is to get the updates of an rtd server in python
I've following call in excel which is working:
=RTD("xrtd.xrtd";;"EUCA")
For python I've found following client library: https://github.com/brotchie/pyrtd/blob/master/rtd/client.py
I tried to get a simple example where I can connect to the server
import sys
sys.path.append(".")
from client import RTDClient
name = "xrtd.xrtd"
try:
client = RTDClient(name)
client.connect(False)
client.register_topic('EUCA')
except Exception as identifier:
print(str(name) + " error : " + str(identifier))
My first problem was that I've used 64bit python, but after I solved this I receive following exception from the connect():
xrtd.xrtd error : This COM object can not automate the makepy process
please run makepy manually for this object
I've no idea what I've to do now. I've python experience but no experience with COM Objects
Try this
import pythoncom
from rtd import RTDClient
if __name__ == '__main__':
time = RTDClient('xrtd.xrtd')
time.connect()
time.register_topic('EUCA')
while 1:
pythoncom.PumpWaitingMessages()
if time.update():
print time.get('EUCA')

Invalid syntax error on python version while running python idle

I am working on a tcp client-server python socket program where I have written server code to sent a simple message to the client . However when I run the server side in python idle I get invlalid syntax error and a red mark on the python version . I don't know where the problem is and I would appreciate your help with this specific task .
Image where error happens :
I press run and then run module and I get :
My code :
Server :
import sys
from socket import *
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('localhost',1234))
serverSocket.listen()
data = "Network labs"
while 1 :
connectionSocket ,addr = serverSocket.accept()
connectionSocket.send(data)
connectionSocket.close()
Client :
import sys
from socket import *
clientSocket = socket(AF_INET,SOCK_STREAM)
server_address=('localhost',1234)
clientSocket.connect(server_address)
sentence = clientSocket.recv(1024)
print(sentence)
clientSocket.close()
You tried to run the log of a shell session, complete with non-code startup message text and non-code prompts as python code. But the session log is not python code. "Python" might be, but "Python 3" is not valid code and so python reports a SyntaxError. This has nothing to do with running the code from an IDLE editor. If you run server.py from a command line or from any other python-aware editor or IDE, you would see the same.
To run server.py, you must remove the non-code parts -- the startup message and prompts. In general, you would also have to remove output, but there is none in your example. So you should end up with
import sys
from socked import *
...
In other words, the cleaned-up server code you listed in your question, which is not the code you ran in the screenshot to get the error message.

How to connect to windows 2012 machine from Centos using Python3

My requirement is ability to run a PowerShell script on a Windows 2012 server remotely, this has to be triggered from a Linux server using Python script.
Need suggestions on best way to handle this and also sample code (if possible).
Below are the steps I intend to achieve but i see it's not working as expected.
PowerShell scripts to be executed are already placed in Windows server (2012).
Python3 program running on Linux (CentOS) does SSH to Windows server (2012) using netmiko module.
sends the command (PowerShell command to execute script in remote Windows server) over the SSH connection.
I was able to connect to the remote Windows server using Python. But I don't see this method working as expected.
Need an effective and efficient way to achieve this.
from netmiko import ConnectHandler
device = ConnectHandler(device_type="terminal_server",
ip="X.X.X.x",
username="username",
password="password")
hostname = device.find_prompt()
output = device.send_command("ipconfig")
print (hostname)
print (output)
device.disconnect()
Nothing much is done for 'terminal_server" device type. You have to do manual passing at the moment.
Below is extracted from COMMON_ISSUES.md
Does Netmiko support connecting via a terminal server?
There is a 'terminal_server' device_type that basically does nothing post SSH connect. This means you have to manually handle the interaction with the terminal server to connect to the end device. After you are fully connected to the end network device, you can then 'redispatch' and Netmiko will behave normally
from __future__ import unicode_literals, print_function
import time
from netmiko import ConnectHandler, redispatch
net_connect = ConnectHandler(
device_type='terminal_server', # Notice 'terminal_server' here
ip='10.10.10.10',
username='admin',
password='admin123',
secret='secret123')
# Manually handle interaction in the Terminal Server
# (fictional example, but hopefully you see the pattern)
# Send Enter a Couple of Times
net_connect.write_channel("\r\n")
time.sleep(1)
net_connect.write_channel("\r\n")
time.sleep(1)
output = net_connect.read_channel()
print(output) # Should hopefully see the terminal server prompt
# Login to end device from terminal server
net_connect.write_channel("connect 1\r\n")
time.sleep(1)
# Manually handle the Username and Password
max_loops = 10
i = 1
while i <= max_loops:
output = net_connect.read_channel()
if 'Username' in output:
net_connect.write_channel(net_connect.username + '\r\n')
time.sleep(1)
output = net_connect.read_channel()
# Search for password pattern / send password
if 'Password' in output:
net_connect.write_channel(net_connect.password + '\r\n')
time.sleep(.5)
output = net_connect.read_channel()
# Did we successfully login
if '>' in output or '#' in output:
break
net_connect.write_channel('\r\n')
time.sleep(.5)
i += 1
# We are now logged into the end device
# Dynamically reset the class back to the proper Netmiko class
redispatch(net_connect, device_type='cisco_ios')
# Now just do your normal Netmiko operations
new_output = net_connect.send_command("show ip int brief")

Telnet connection to TS3 ServerQuery keeps getting slower and slower

I wrote a bot for TeamSpeak 3 that runs over ServerQuery (a telnet interface).
But the bot keeps responding later and later, in the beginning it takes like 0.1 sec, after like 1 minute the bot takes about 10 seconds to respond, and using commands makes it even faster.
Any idea why?
So basically the telnet interface sends data from the TS3 Server to my python script, the ts3 module recieves and processes the data, then the script will make a decision of what the action will be.
As modules I am using MySQLdb and ts3(https://github.com/benediktschmitt/py-ts3)
My sourcecode is here: https://pastebin.com/cJuyB9ZH
Another script, which just takes all clients and pushes them into a database every 5 min, runs multiple days without any issues.
I checked the code multiple times now and even deleted variables right after they have been used, but it still has the same issue.
My guess would be that is sortof clogges the RAM, so I looked through the code multiple times, but couldn't find out why or where.
Sidenote: I know I sometimes call a commit() when its totally not necessary, but I don't know if that might cause problems, but I dont see how.
Short(er) version of my code:
import ts3
import MySQLdb
# Some other imports like time and threading and such
## Connect to TS3
tsConn = ts3.query.TS3Connection(tsAddr, tsPort)
try:
tsConn.login(client_login_name=tsUser, client_login_password=tsPass)
tsConn.use(sid=tsSID, virtual=True)
print(" ==>> CONNECTED TO TS3 SERVER: " + tsAddr)
except ts3.query.TS3QueryError as e:
print("Login to TS Server failed! Aborting...")
exit(1)
## Connect to mySQL
try:
qConn = MySQLdb.connect(host=qHost, user=qUser, passwd=qPass, db=qDB)
qServer = qConn.cursor()
print(" ==>> CONNECTED TO mySQL SERVER: " + qHost)
except OperationalError:
print("Cannot connect to mySQL Database! Aborting...")
exit(1)
running = True
while running:
tsConn.send_keepalive()
qServer.execute("SELECT 1") # keepalive
try:
e = tsConn.wait_for_event(timeout=1)
except TS3TimeoutError:
pass
else:
try:
# <some command processing here>
except KeyError:
try:
if event[0]["reasonid"] == "0":
tsConn.sendtextmessage(targetmode=1, target=event[0]["clid"], msg=greetingmsg.format(event[0]["client_nickname"]))
except:
pass

python script in relation to the spike fuzzer connecting to vulnserver.exe

ok so i have vulnserver.exe running on my win7 box waiting for input on port 9999. It takes in certain commands with parameters one of which is TRUN and is designed to trigger a buffer overflow if the TRUN parameters are the right length:
this is the python im running on kali linux to try to connect to vulnserver and see if can cause a crash:
import socket
numAs = 10
try:
while True:
# open a connection to vulnserver
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
s.connect (("194.168.1.154", 9999))
# receive the banner for vulnserver
s.recv (1024)
print "[*] Sending " + str(numAs) + " As"
# send the number of As to fuzz the HTER command
s.send ("HTER " + "A" * numAs + " \r\n")
# receive the response from vulnserver
s.recv (1024)
# close the connection
s.close ()
# increase the number of As we send next time
numAs += 10
except:
# if we get to here then something happened to vulnserver because the
connection is closed
print "Socket closed after sending " + str(numAs - 10) + " As"
however here is the command line output im getting
./hterfuzz.py: line 2: numAs: command not found
./hterfuzz.py: line 3: try:: command not found
./hterfuzz.py: line 6: syntax error near unexpected token `('
./hterfuzz.py: line 6: `s = socket.socket (socket.AF_INET,socket.SOCK_STREAM)'
Im very new to python and dont understand some basic errors so any help would be greatly appreciated. Thanks so much !
also the vulnserver.exe program is available here :
http://sites.google.com/site/lupingreycorner/vulnserver.zip
and the tutorial on fuzzing using vulnserver is here:
https://samsclass.info/127/proj/vuln-server.htm
if there is any other info I can provide just ask, Im simply trying to fix the errors in the py script so I can play around with it to try and find out whats needed to cause the overflow and eventually modify it to create a useful input string to execute processes on the win7 box by sending the string to vulnserver.
Thanks for any help people :)
Quite a simple one this - your script is being interpreted by bash, not python.
Just add this as the first line of your code: #!/usr/bin/python

Categories

Resources