How can I use a table in LUA for pinging multiple devices and detecting change in variable status - arrays

I am trying to ping a number of IP address on a local network at defined intervals and then send a message only when a device connects. I have managed to get it to work for a single device, but when I add additional devices to the table the code fails.
Many thanks in advance.
An earlier version without the table and just a single IP address works perfectly. But adding the table and the "for key,value loop" only works if a single entry is in the table.
local tble = {
["device name"] = "192.168.1.204"
}
for key,value in pairs(tble) do
statuscheckIP=os.execute("arping -f -w 3 " .. value)
if statuscheckIP ~= lastcheckIP then
if statuscheckIP == 0 and lastcheckIP == 256 then
subject ="" ..key.. " , ( IP Address " ..value.. ") Connected"
message = "Connection Alert\nThe device named " ..key.. ", with the IP address " ..value.. " has just connected to the WiFi network"
--send email notification
luup.call_action("urn:upnp-org:serviceId:SmtpNotification1", "SendEmail", { Recipient_Name="SomeOne", Recipient_eMail="someone#somewhere.com", Subject= subject, Message=message }, 24)luup.call_action("urn:upnporg:serviceId:SmtpNotification1","ResetCount",{}, 24)
else
end
end
end
lastcheckIP = statuscheckIP

The code you posted is valid. There are not many reasons why this would fail due to more entries in your table.
os.execute Execute an operating system shell command. This is like the C system() function. The system dependent status code is returned.
Running os.execute will start a arping and return an exitcode. Then you are comparing that statuscheckIP == 0 a lastcheckIP == 256. The if before is redundant. If true you are sending your message and continuing.
After worked though all entries you are setting lastcheckIP to statusCheckIP and this is propably your error. It should be before the last if and inside your loop. But even then does not make sense if 0 is the only correct return code. If lastcheckIP is set to any other value your both if's will never go true again.
Either your last line lastcheckIP = statuscheckIP is wrongly placed, lastcheckIP was never initialized to 256 or you should rethink your whole program.
EDIT:
After understanding the intention of the provided program, I've created a probably working example. This should show you, how to easily use tables in Lua as a structures. I was not able to test the following code.
local WAIT_TIME = 10
local STATUS_CODE_CONNECTED = 0
local STATUS_CODE_NOT_CONNECT = 256 -- not sure about this (return code from arping for failure)
local device_table =
{
["device_name1"] =
{
ip = "<ip address>",
status_code = STATUS_CODE_NOT_CONNECT
},
["device_name1"] =
{
ip = "<ip address>",
status_code = STATUS_CODE_NOT_CONNECT
}
-- , ...
}
while true do
-- check for changed return codes
for device_name, device in pairs(device_table) do
local temp_status_code = os.execute("arping -f -w 3 " .. device.ip)
-- status code changed
if temp_status_code ~= device.status_code then
-- device connected
if temp_status_code == STATUS_CODE_CONNECTED then
local subject = "" .. device_name .. " , ( IP Address " .. device.ip .. ") Connected"
local message = "Connection Alert\nThe device named " .. device_name .. ", with the IP address " .. device.ip .. " has just connected to the WiFi network"
--send email notification
luup.call_action(
"urn:upnp-org:serviceId:SmtpNotification1",
"SendEmail",
{
Recipient_Name = "SomeOne",
Recipient_eMail = "someone#somewhere.com",
Subject = subject,
Message = message
}, 24)
luup.call_action(
"urn:upnporg:serviceId:SmtpNotification1",
"ResetCount",
{ }, 24)
end
-- update last device status_code if changed
device.status_code = temp_status_code
end
end
os.execute("sleep " .. tonumber(WAIT_TIME)) -- wait some time for next check
end
If I've understand you wrongly and you either do not want to have this program run all the time or do not want to have all addresses in a table then you should ask again or somewhere else because that would be out off topic.

Related

Is there a way to check if any content of a array is in another array in Roblox

So I am trying to make a script which allows me to ban people but the main script which checks if a player is in the game and in the banned users list to be killed or kicked. Here is my code:
local BannedUsers = {"littleBitsman"}
local Players = game.Players:GetChildren()
wait(10)
for index1,value1 in ipairs(Players) do
for index2,value2 in ipairs(BannedUsers) do
if Players[index1] == BannedUsers[tonumber(index2)] then
local HumanoidToKill = workspace[value1].Character:FindFirstChildWhichIsA("Humanoid")
if HumanoidToKill.Health >= 0 then
HumanoidToKill.Health = 0
print("killed " .. tostring(value1))
end
end
end
end
The wait(10) is so I can test the script without executing too early, and the use of my username is for testing.
Also when I do test it it does nothing at all.
You can use the table.find function.
local BannedUsers = {"littleBitsman"}
for _, player in ipairs(game.Players:GetChildren()) do
if table.find(BannedUsers, player.Name) then
player:Kick("You are banned!")
end
end

Connection from sites using the websocket protocol. Ruby

There is a program that connects to the server and receives some data from it + counts server time and signals every 15 or 60 seconds.
require 'faye/websocket'
require 'eventmachine'
data = []
count = 0
EM.run {
ws = Faye::WebSocket::Client.new('wss://olymptrade.com/ws2')
ws.on :open do |event|
p [:open]
ws.send('{"uuid":"JCBQ7XBRMYSL0JB4N5","pair":"Bitcoin","size":60}')
end
ws.on :message do |event|
p [:message, event.data]
data << event.data
data_servertime = data[0].gsub(/[^\d]/, '').to_i
data.delete_at(0)
if ((data_servertime % 15) == 0)
puts "Прошло 15 секунд"
elsif ((data_servertime % 60) == 0)
puts "Прошло 60 секунд"
end
end
ws.on :close do |event|
p [:close, event.code, event.reason]
ws = nil
end
}
At startup, it constantly outputs the received data to the console:
[:message, "{\"pair\":\"Bitcoin\",\"time\":1516567298,\"open\":11146.938,\"low\":11146.938,\"high\":11146.938,\"close\":11146.938}"]
[:message, "{\"servertime\":1516567298}"]
My Questions:
How do I put the rest of the data in the array (except for servertime) namely: pair,time,open,low,high,close?
How to make it so that ONLY the information displayed on the screen is displayed, which I intentionally output using the puts command?

Splitting String into Array Errors

Trying to write a script that will be run in WinPE, that essentially gets the IP address of the localhost and chooses an action based on the IP range.
In Windows, the script runs flawlessly. However, in WinPE, I'm getting the following error:
script.vbs(1,1) Microsoft VBScript runtime error: Subscript out of range
Google-fu is telling me that has something to do with my array being outside of the range. Here I thought I had a decent understanding, but apparently not.
Code that works as is on Windows:
Option Explicit
Dim sIP, sHostname,sPingBat
Dim aIP
Dim iOct1, iOct2, iOct3, iOct4, iReturn
Dim oWMIService, oCmd, oAdapter
Dim cAdapters
iReturn = 999
sHostname = "."
Set oWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sHostname & "\root\cimv2")
Set cAdapters = oWMIService.ExecQuery("Select IPAddress from Win32_NetworkAdapterConfiguration Where IPEnabled = True")
Set oCmd = CreateObject("Wscript.Shell")
For Each oAdapter in cAdapters
If Not IsNull(oAdapter.IPAddress) Then
sIP = Trim(oAdapter.IPAddress(0))
Else
iReturn = 404
WScript.Quit iReturn
End If
Next
sIP = CStr(sIP)
aIP = Split(sIP, ".")
iOct1 = CInt(aIP(0))
iOct2 = CInt(aIP(1))
iOct3 = CInt(aIP(2))
iOct4 = CInt(aIP(3))
Now, if I change the declaration of the aIP array to either of the following:
aIP()
aIP(4)
and run
aIP = Split(sIP, ".")
I get
script.vbs(26, 1) Microsoft VBScript runtime error: Type mismatch
Changing the array assignment / split line to
aIP() = Split(sIP,".")
results in
script.vbs(26, 1) Microsoft VBScript runtime error: Subscript out of range
So I'm obviously doing something wrong.
It's also entirely possible that my original error message is completely unrelated to my array range, and WinPE just doesn't like my script (in which case, if anybody has any pointers, it'd be appreciated)
At the moment, I'm mounting my wim to get the install packages to make sure the WMI and Scripting packages are installed from the ADK.
There is nothing wrong with the code except the assumption being made about what Win32_NetworkAdapterConfiguration returns.
From MSDN - Win32_NetworkAdapterConfiguration class
Array of all of the IP addresses associated with the current network adapter. This property can contain either IPv6 addresses or IPv4 addresses. For more information, see IPv6 and IPv4 Support in WMI.
Because sIP could contain an IPv6 address the Split() will not work as expected. IPv6 addresses don't contain . as a separator so Split() will return a Array containing the original string as the first index only. Hence attempting to read anything other then aIP(0) will cause an
Microsoft VBScript runtime error:
Subscript out of range
error.
To avoid this use InStr() to check for the existence of . in the sIP variable first, you will also need to iterate through the oAdapter.IPAddress array to check each address to get the correct one, you can't assume IPAddress(0) will always be the right one.
Try this
Dim ips, ip
For Each oAdapter in cAdapters
ips = oAdapter.IPAddress
If IsArray(ips) Then
For Each ip In ips
If InStr(1, ip, ".") > 0 Then
sIP = Trim(ip)
Exit For
End If
Next
If Len(sIP) > 0 Then Exit For
Else
iReturn = 404
WScript.Quit iReturn
End If
Next
Untested on iPad sorry
I guess sIP variable contains some string which can not be splitted wity delimiter "."(ex: "somestringwithNoDOT")
So in the 1st case
aIP = Split(sIP,".") ' Split("somestringwithNoDOT",".")
statement returned only 1 string, which can not be coverted to Integer. So i returned Type mismatch error in below line
iOct1 = CInt(aIP(0)) ' returns Type mismatch error
In the 2nd case
aIP() = Split(sIP,".") ' Split("somestringwithNoDOT",".")
above statement will return 1 element, but aIP is array with NO elements. So this statement rturned "Subscript out of range" error
Resolution for this issue is to check whether correct value is passing to sIP

repeating program (python)

Heyho
I want to repeat a program after runnning a task. At the start of the program I ask some questions, than the code jumps into the task. If the task is done the questions sholud ask again..
Each Question reads some infos at the serial port. If i get the infos ten times ich will restart the programm.. but the window closes and i must start the file..
What can i do?
import serial
import struct
import datetime
print("\n")
print("This tool reads the internal Bus ")
print("-----------------------------------------------------------------------")
COM=input("Check your COM Port an fill in with single semicolon (like: 'COM13' ): ")
ser = serial.Serial(
port=COM,
baudrate=19200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
print("\n")
print("Please choose an option: ")
print("Polling of measured values and the operating status (1)")
print("Reading Parameter memory (2)")
print("Reading Fault memory (3)")
print("EXIT (4)")
print("\n")
i=input("Reading: ")
while(i==1):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x14\x75\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(46))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Values: ,")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
loop=1
#-----------------------------------------------------------------------
while(i==2):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x13\x00\x00\x74\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(11))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Parameters: , ")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
#---------------------------------------------------------------------
while(i==3):
count=0
while (count<10):
print(file.name)
print(ser.isOpen())
print ("connected to: "+ ser.portstr)
data = "\xE1\x12\x00\x00\x73\x81"
ser.write(data)
a=(map(hex,map(ord,ser.read(11))))
with open("RS485_Reflex.txt",mode='a+') as file:
file.write(str(datetime.datetime.now()))
file.write(", Fault: , ")
file.write(str(a))
file.write("\n")
print(a)
count=count+1
else:
i=0
#----------------------------------------------------------------------
while(i==4):
file.close()
ser.close()
sys.exit(0)
file.close()
ser.close()
First, you should use If/Elif/Else statements instead of while loops.
while(i==1):
should be
if(i==1)0:
This is a simple program I wrote that you can follow:
# setup a simple run_Task method (prints number of times through the loop already)
def run_task(count):
print "Ran a certain 'task'", count,"times"
# count is a variable that will count the number of times we pass through a loop
count = 0
# loop through 10 times
while(count<10):
# ask questions
q1 = raw_input("What is your name?")
q2 = raw_input("What is your favorite color?")
# run a 'task'
run_task(count)

SNMP GetNext Command

I am having a MIB which contain table structure and i have generate code for that with the help of mib2c command in the Net-SNMP Library
mib2c -c mib2c.create-dataset.conf IPsTable
It generates the two files IPsTable.c and IPsTable.h.
Actually when i send a command for snmpwalk
snmpwalk -v2c -c public localhost -Ci IPsTable
Its give an output thats states "Error: OID not increasing "
I have traced the log and got to know that we receive only the GET NEXT request and the value of column field increases everytimes i got the request.
case MODE_GETNEXT:
var = request->requestvb;
table_info = netsnmp_extract_table_info(request);
snmp_log(LOG_INFO,"column : %d\n",table_info->colnum);
snmp_log(LOG_INFO,"index : %d\n",*(table_info->indexes->val.integer));
if (table_info->colnum > RESULT_COLUMN){
table_info->colnum=0;
return SNMP_ERR_NOERROR;
}
x=*(table_info->indexes->val.integer);
netsnmp_table_build_result(reginfo, requests,
table_info, ASN_INTEGER,
(u_char *) & result,
sizeof(result));
break;
Problem arises when the value of column exceed from the number of column we have in MIB's row and its keeps on increasing. I was not been able to increment the value of index.
Is there any way so that i can reset the value of column and incement the value of index (means pointing to next row) ?

Resources