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.
Related
Environment:
Python 3.7.7
Windows 10 64bits
Problem:
I have my main script doing some stuff. I need to display a report of its activities.
I made a mini website which display the data activity.
I placed this mini website in a subfolder ‘/report’.
Inside this subfolder ‘/report’, I have the script Report.py which launch the http.server
My main script is executing this Report.py in order to open the mini website in a browser. Since 3 days I am working on it and I didn’t succeed to make it work.
So this is how my code is organized:
main.py
report/Report.py
report/index.py
here is main.py:
from report import Report
Report.StartReportTool()
and here is what I tried inside the Report.py file and which error I get. These codes below are the content of method "StartReportTool()":
N°1:
port=8888
address=("",port)
server=http.server.HTTPServer
handler=http.server.CGIHTTPRequestHandler
handler.cgi_directories=["report"]
httpd=server(address,handler)
print(f"Report tool server started on port {port}")
webbrowser.open(f'http://localhost:{port}/report/index.py', new=2)
httpd.serve_forever()
Error: The browser open url ‘http://localhost:8888/report/index.py’display the source code of index.py instead of executing the script index.py
================================
N°2 I edited the url pass to webbrowser.open
port=8888
address=("",port)
server=http.server.HTTPServer
handler=http.server.CGIHTTPRequestHandler
handler.cgi_directories=["report"]
httpd=server(address,handler)
print(f"Report tool server started on port {port}")
webbrowser.open(f'http://localhost:{port}/index.py', new=2) #<= I change this line
httpd.serve_forever()
Error: The browser opens this URL ‘http://localhost:8888/index.py’ and displays this error message:
Error response
Error code: 404
Message: File not found.
Error code explanation: HTTPStatus.NOT_FOUND - Nothing matches the given URI.
================================
N°3
I edited the folder pass to handler.cgi_directories
port=8888
address=("",port)
server=http.server.HTTPServer
handler=http.server.CGIHTTPRequestHandler
handler.cgi_directories=["/"] #<= I change this line
httpd=server(address,handler)
print(f"Report tool server started on port {port}")
webbrowser.open(f'http://localhost:{port}/index.py', new=2)
httpd.serve_forever()
Error: The browser opens this URL ‘http://localhost:8888/index.py’ and shows this error message in the browser:
Error response
Error code: 404
Message: No such CGI script ('//index.py').
Error code explanation: HTTPStatus.NOT_FOUND - Nothing matches the given URI.
I don’t know what else to try. Does anyone have any idea what am I doing wrong?
This worked for me (notice the slash):
handler.cgi_directories=["/report"]
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')
I have a python script that uses the http.server module that I would like to run without a terminal window being shown. Unfortunately, due to how I'm doing this, running the script in pythonw.exe does not work.
Here is the script:
import os
from http.server import CGIHTTPRequestHandler, HTTPServer
handler = CGIHTTPRequestHandler
handler.cgi_directories = ['/scripts']
server = HTTPServer(('localhost', 1271), handler)
server.serve_forever()
Unfortunately, I don't know any way get any error logs because, y'know, pythonw doesn't show the console. If anyone can tell me how to get the error logs, I'll be happy to add them to the bottom of this post.
I'm running 64-bit Windows 10 and python 3.6.6, if that makes a difference.
I'm sorry if this is a stupid question, but I—for the life of me—cannot find a solution anywhere.
You can just store output to a text file like this:
from http.server import CGIHTTPRequestHandler, HTTPServer
import sys
handler = CGIHTTPRequestHandler
handler.cgi_directories = ['/scripts']
server = HTTPServer(('localhost', 1271), handler)
sys.stderr = open('log.txt', 'w', 1)
server.serve_forever()
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")
I want to send some file from a client PC to a server PC using Python.
But when I run the client code, there is a problem.
Here is the client code:
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as sock:
sock.connect((HOST,PORT))
sock.sendall(filename.encode('utf-8'))
print(filename.encode('utf-8'))
and this is the server code:
filename = self.request.recv(1024)
print(filename)
filename = filename.decode('utf-8')
When I run it within my PC (for example, server=client localhost), it runs perfectly.
But in my server PC, print result has some added text like:
b'filename\~~~~~~~~~~'
filename result
error message
So I think if the added text is gone when I use my server PC, the problem will be solved.
But I dont know how to get there.
Please let me know...