Working on a script that checks IP and then closes notepad2.exe if IP is not equal. Problem is that script closes notepad2.exe regardless.
#SingleInstance
#Persistent
Settimer, CheckIP, 500
vIPaddress = "192.168.1.14"
CheckIP:
vCurrentaddr = %A_IPAddress1%
if (vIPaddress <> vCurrentaddr)
{
Process, Close, Notepad2.exe
}
return
f10::exitapp ; when I need to stop watchdog
edit:
corrected script so now it doesn't shut down notepad2.exe all the time, but now problem it doesn't update value for vCurrentaddr = %A_IPAddress1%. Now it doesn't close notepad2.exe with:
if (vIPaddress <> vCurrentaddr)
#SingleInstance
#Persistent
Settimer, CheckIP, 500
vIPaddress = 192.168.1.4
CheckIP:
vCurrentaddr = %A_IPAddress1%
vCurrentaddr2 = %A_IPAddress2%
if (vIPaddress <> vCurrentaddr)
{
Process, Close, Notepad2.exe
}
else if (vCurrentaddr2 <> "0.0.0.0")
{
if (vIPaddress <> vCurrentaddr2)
{
Process, Close, Notepad2.exe
}
}
return
f10::exitapp ; when I need to stop watchdog
This seems to work as vCurrentaddr2 holds the changed IP. When not connected to a VPN the value is 0.0.0.0 and after connecting to VPN the value changes.
edit:
cleaning up code for uneeded statements!
Related
I have a program which connects to a bunch of hosts and checks if they are "socket reflectors". Basically, it is scanning a bunch of ips and doing this:
Connect, check - if there is data, is that data the same as what I am sending? Yes, return true, no return false. No data, return false.
For some reason, asyncio is not reliably closing TCP connections after they time out. I attribute this to the fact that a lot of these hosts I am connecting to are god knows what, and maybe just buggy servers. Be that as it may, there must be a way to make this force timeout? When I run this, it hangs after a while. Out of 12,978 hosts, about 12,768 of them complete. Then I end up with a bunch of open ESTABLISHED connections! Why does this happen?
I need it close the connection if nothing happens during the given timeout period.
async def tcp_echo_client(message, host_port, loop, connection_timeout=10):
"""
Asyncio TCP echo client
:param message: data to send
:param host_port: host and port to connect to
:param loop: asyncio loop
"""
host_port_ = host_port.split(':')
try:
host = host_port_[0]
port = host_port_[1]
except IndexError:
pass
else:
fut = asyncio.open_connection(host, port, loop=loop)
try:
reader, writer = await asyncio.wait_for(fut, timeout=connection_timeout)
except asyncio.TimeoutError:
print('[t] Connection Timeout')
return 1
except Exception:
return 1
else:
if args.verbosity >= 1:
print('[~] Send: %r' % message)
writer.write(message.encode())
writer.drain()
data = await reader.read(1024)
await asyncio.sleep(1)
if data:
if args.verbosity >= 1:
print(f'[~] Host: {host} Received: %r' % data.decode())
if data.decode() == message:
honeypots.append(host_port)
writer.close()
return 0
else:
filtered_list.append(host_port)
print(f'[~] Received: {data.decode()}')
writer.close()
return 1
else:
filtered_list.append(host_port)
writer.close()
if args.verbosity > 1:
print(f'[~] No data received for {host}')
return 1
What am I doing wrong?
I am experimenting with Arduino and ESP8266 module, and now I am trying to send some sensor data to a TCP server. For this purposes I am using AT+CIPSTART command (to establish a TCP connection) and AT+CIPSEND to send the data.
If I am testing it using Serial Monitor, it works fine. After entering CIPSEND command I can write some text in a terminal and this message/text will be sent to the TCP server.
When I am trying to make it inside Arduino sketch, then it sends an empty message. The connection works, but I do not see any data.
How can I send a message text (msg) with my TCP packet?
Here is a code snippet
// ESP8266 Client
String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
cmd += IP;
cmd += "\",3103";
sendDebug(cmd);
delay(2000);
if( Serial.find( "Error" ) )
{
debug.print( "RECEIVED: Error\nExit1" );
return;
}
String msg = "test";
Serial.print( "AT+CIPSEND=" );
Serial.println( msg.length() );
if(Serial.find( ">" ) )
{
debug.print(">");
debug.print(msg);
Serial.print(msg);
}
else
{
sendDebug( "AT+CIPCLOSE" );//close TCP connection
}
if( Serial.find("OK") )
{
debug.println( "RECEIVED: OK" );
}
else
{
debug.println( "RECEIVED: Error\nExit2" );
}
}
First of all, Select how much character or byte is needed to transmit. It is better to use softwareSerial library to connect with ESP8266 and send AT commands.
Suppose yow want to send 5 bytes.Type the following AT commands and must give a delay more than 100 millisecond before sending data. Here "\r" is carriage return and "\n" is new line. After including this, ESP8266 can understand you have ended the command.
esp.print("AT+CIPSEND=5\r\n");
delay(1000);
esp.print("Hello");
Your code is not working because you are using unvarnished transmission mode. So to complete a packet you need to transmit 2048 bytes which you are not writing.
I have a problem using latest Copas in Lua 5.2.
I wrote a simple script (see below) which creates two server sockets: "RX" and "TX".
"RX" listens for messages from connected clients, "TX" transmits those messages to clients connected to "TX".
The problem is: In the beginning, after server start-up, everything works fine. But after a certain amount of messages, the "TX" server loop is not executed anymore, no more messages are transmitted.
There is no error message, nothing. It just stops working.
Am I using Copas wrong? What is the problem?
This is the (simplified) code:
local copas = require("copas")
local socket = require("socket")
local pl_class = require("pl.class")
-- Connection between a server and a client
pl_class.ClientConnection()
function ClientConnection:_init(connectionName, socketToClient)
self.connectionName = connectionName
self.socketToClient = socketToClient
self.queueMessagesToSend = {}
end
function ClientConnection:popMessageToSend()
return table.remove(self.queueMessagesToSend, 1);
end
function ClientConnection:pushMessageToSend(theMessage)
table.insert(self.queueMessagesToSend, theMessage)
end
-- Server base class
pl_class.Server()
function Server:_init(serverName, serverPort)
self.serverName = serverName
self.serverPort = serverPort
self.connectedClients = {}
end
function Server:initServing()
local server = socket.bind("*", self.serverPort)
print("[" .. self.serverName .. "] Waiting for client connections on port " .. self.serverPort .. "...")
copas.addserver(server, function(c) return self.connectionHandler(copas.wrap(c), c:getpeername()) end )
end
-- Class for send-only servers
pl_class.ServerSendOnly(Server)
function ServerSendOnly:_init(serverName, serverPort)
self:super(serverName, serverPort)
self.connectionHandler = function (socketToClient, clientHost, clientPort)
local connObject = ClientConnection(clientHost..":"..tostring(clientPort), socketToClient)
self.connectedClients[connObject.connectionName] = connObject
while true do
local currMessage = connObject:popMessageToSend()
if currMessage then
copas.send(connObject.socketToClient, currMessage)
end
copas.sleep(0.01)
end
self.connectedClients[connObject.connectionName] = nil
end
end
function ServerSendOnly:broadcastMessage(currMessage)
for connName,connObject in pairs(self.connectedClients) do
connObject:pushMessageToSend(currMessage .. "\r\n")
end
end
-- Class for receive-only servers
pl_class.ServerReceiveOnly(Server)
function ServerReceiveOnly:_init(serverName, serverPort)
self:super(serverName, serverPort)
self.queueMessagesReceived = {}
self.connectionHandler = function (socketToClient, clientHost, clientPort)
local connObject = ClientConnection(clientHost..":"..tostring(clientPort), socketToClient)
self.connectedClients[connObject.connectionName] = connObject
while true do
local currDataReceived = copas.receive(connObject.socketToClient)
if currDataReceived ~= nil then
local currInfo = {client=connObject.connectionName, data=currDataReceived}
table.insert(self.queueMessagesReceived, currInfo)
end
end
self.connectedClients[connObject.connectionName] = nil
end
end
function ServerReceiveOnly:popMessageReceived()
return table.remove(self.queueMessagesReceived, 1);
end
-- Setup servers
local serverSend = ServerSendOnly("ServerTX", 2345)
local serverReceive = ServerReceiveOnly("ServerRX", 1234)
serverSend:initServing()
serverReceive:initServing()
-- Main loop: Pass messages which arrived at the RX server to the clients
-- connected to the TX servers ("RX" and "TX" are used from the server's POV)
while true do
copas.step()
local currMessage = serverReceive:popMessageReceived()
if currMessage then
print("[" .. serverReceive.serverName .. "] MESSAGE RECEIVED FROM '" .. currMessage.client .."': " .. currMessage.data)
serverSend:broadcastMessage(currMessage.data)
end
end
I'm absolute beginner for python Tkinter. My program has serial port and TCP client socket connection (Running in thread). It's running well in console application but not work in Tkinter GUI.
count = 0
initialState = True
def initState(reader, ReaderName, readerType, serialport, baud, databit, readerPacket):
global count
global initialState
if initialState:
while not reader.SettingReader(ReaderName, readerType, serialport, baud, databit, readerPacket):
count += 1
count = 0
labelSearching.place(x=290, y=260)
labelReaderSetting.configure(image=readerSettingSuccess)
app.update_idletasks()
labelSearching.grid_forget()
labelReaderConnect.place(x=290, y=260)
app.update_idletasks()
labelReaderConnect.configure(image=readerConnected)
labelServerConnect.place(x=290, y=320)
app.update_idletasks()
while not reader.StartServer():
count += 1
count = 0
labelServerConnect.configure(image=serverConnected)
app.update_idletasks()
labelContainer.grid_forget()
labelReaderSetting.configure(image=readerSettingSuccessSmall)
labelReaderSetting.place(x=80, y=200)
labelReaderSetting.lift()
labelReaderConnect.configure(image=readerConnectedSmall)
labelReaderConnect.place(x=80, y=260)
labelReaderConnect.lift()
labelServerConnect.configure(image=serverConnectedSmall)
labelServerConnect.place(x=80, y=320)
labelServerConnect.lift()
labelWaitingTap.place(x=460, y=260)
labelLeft.grid(row=1, column=0)
labelRight.grid(row=1, column=1)
app.update_idletasks()
reader.SaveSettingToFile()
initialState = False
else:
runnMainProgram(reader)
app.update()
app.after(1000, functools.partial(initState, reader, ReaderName, readerType, serialport, baud, databit, readerPacket))
def runnMainProgram(reader):
try:
check = reader.StartReader(reader._CARDANDPASSWORD)
app.update_idletasks()
if check == True:
print "Open the door"
check = ""
print "Ready..."
app.update_idletasks()
elif check == False:
print "Doesn't Open The Door"
check = ""
print "Ready..."
app.update_idletasks()
elif check == 2:
print "Reader disconnect"
print "Reconnecting to Reader"
reader.ClosePort()
while not reader.OpenPort():
count += 1
count = 0
check = ""
print "Ready..."
app.update_idletasks()
except KeyboardInterrupt:
exit()
app.after(10, functools.partial(runnMainProgram, reader))
app = Tk()
app.title("Access Control")
app.geometry('800x610+200+50')
app.protocol('WM_DELETE_WINDOW', closewindow)
updateGUIThread = threading.Thread(target=updateGUI)
app.minsize('800', '610')
app.maxsize('800', '610')
"I'm create Tkinter widget here."
reader = Readers()
settingList = list()
readerType = ""
readerPacket = ""
try:
for line in fileinput.FileInput("Setting.txt", mode='r'):
settingList.append(line)
if str(line).find("DF760MSB", 0, len(str(line))) >= 0:
readerType = reader._DF760MSB
elif str(line).find("DF760LSB", 0, len(str(line))) >= 0:
readerType = reader._DF760LSB
else:
readerType = reader._DF760MSB
if str(line).find("SINGLEPACKET", 0, len(str(line))) >= 0:
readerPacket = reader.SINGLEPACKET
elif str(line).find("MULTIPACKET", 0, len(str(line))) >= 0:
readerPacket = reader.MULTIPACKETS
else:
readerPacket = reader.SINGLEPACKET
ReaderName = str(settingList[0]).rstrip()
baud = int(settingList[1])
databit = int(settingList[2])
HOST = str(settingList[3]).rstrip()
PORT = int(settingList[4])
TIMEOUT = int(settingList[5])
except:
ReaderName = "R001"
baud = 19200
databit = 8
HOST = "10.50.41.81"
PORT = 43
TIMEOUT = 10
serialport = 'COM3'
reader.SettingServer(HOST, PORT, TIMEOUT)
app.after(100, functools.partial(initState, reader, ReaderName, readerType, serialport, baud, databit, readerPacket))
app.mainloop()
when I'm run this code GUI will freezing but serial port and TCP client socket still running.
I've try to fix this problem (looking in every where) but I'm got nothing. Any idea? Thank so much.
The way to solve this would be to call app.after(100, <methodName>) from the receiving thread. This stops the main thread from being blocked by waiting for a signal, but also means that tkinter can update instantly too as the method pushed to .after will be executed in the main thread. By specifying 100 as the time frame, it will appear to change nigh on instantly as the argument passed is the number of milliseconds.
I'm trying to make rereading config file for simple perl daemon on SIGHUP.
I'm trying
use sigtrap qw/handler rereadconf HUP/;
but after executing "rereadconf" procedure process stops
i'm also trying
%SIG{HUP} = \&rereadconf;
sub rereadconf{
.... mycode
print "procedure executed\n";
};
but result was the same, after executing procedure program stops.
So how can i make that process continue execution after signal handling?
Your program exits because the accept returns false because it got interrupted by a signal. You want
while (1) {
my $client = $srv->accept();
if (!$client) {
next if $!{EINTR};
die(sprintf(STDERR "[%s] accept: %s\n", basename($0), $!));
}
print(STDERR "accepted new client\n");
serve_client($client);
}