vb.net user input into url - vb.net

I am currently making a VB.net console application that calls upon a web based API to get results back into the console.
What I would like to do is allow the user to input the IP themselves.
Dim sURL As String
sURL = "http://api.hackertarget.com/geoip/?q=1.1.1.1"
I would like to be able to replace the 1.1.1.1 with a user input
Thank you
EDIT:
When I run the program I need to insert the IP twice into the console
Dim nL As String = Environment.NewLine
Console.Write("Please enter an IP Address: ")
Dim input = Console.ReadLine()
This is my code I use to take the user input
EDIT2:
Full Code
Imports System
Imports System.Net
Imports System.IO
Module Module1
Sub Main()
IP:
Dim nL As String = Environment.NewLine
Console.Write("Please enter an IP Address: ")
'Console.WriteLine()
Dim input = Console.ReadLine()
Dim sURL As String
sURL = "http://api.hackertarget.com/geoip/?q=1.1.1.1".Replace("1.1.1.1", Console.ReadLine())
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
Dim myProxy As New WebProxy("myproxy", 80)
myProxy.BypassProxyOnLocal = True
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream()
Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
Dim i As Integer = 0
Do While Not sLine Is Nothing
i += 1
sLine = objReader.ReadLine
If Not sLine Is Nothing Then
Console.WriteLine("{0}:{1}", i, sLine)
End If
Loop
Console.ReadLine()
GoTo IP
End Sub
End Module

You should use -
Dim sURL As String
Console.Write("Please enter an IP Address: ")
sURL = "http://api.hackertarget.com/geoip/?q=1.1.1.1".Replace("1.1.1.1", Console.ReadLine())

Related

Picking out 1 specific string from a file

Ive put in multiple strings in 1 line of a file, so that they are linked together, I have tried multiple ways such as using loops and I was wondering if if anyone could help me, thanks.
in file: swagman (username), samfisher34 (password), sam fisher (fullname)
Private Sub btn_login_Click(sender As Object, e As EventArgs) Handles btn_login.Click
Dim Student As New StreamReader("student.txt")
Dim newline As String
Dim login As Boolean
Dim line1 As String
Dim line2 As String
' Reads the files to a string and write the string to the console.
Dim count As Integer = 20
For i = 1 To count
newline = Student.ReadLine
If txt_login.Text = newline And txt_password.Text = newline Then
'Checks to see if text is the same in the Files.
login = True
End If
If login = True Then
Me.Hide()
StudentMenu.Show()
End If
Next
If login = False Then
MsgBox("login or password is incorrect")
End If
Student.Close()
End Sub
Here is a really basic code example that I made:
First of all you need to import System.IO for the StreamReader
Dim objStreamReader As StreamReader
Dim strLine As String
objStreamReader = New StreamReader(File)
Dim splitresult As Array
'read the file line for line
Do Until objStreamReader.Peek = -1
strLine = objStreamReader.ReadLine
'split the results (user,pwd,name)
splitresult = strLine.Split(",")
If splitresult(0) = user Then
If splitresult(1) = pwd Then
MsgBox("Welcome " & splitresult(2))
End If
Loop
Also please don't store your password as plain text.

Visual Basic: i have a file containg usernames and passwords but i want to read them back in so the user can log back in

Do
Do
Console.WriteLine("Create a password. It must be 8 characters in length")
password1 = Console.ReadLine()
Loop Until password1.Length = 8
Console.WriteLine("Please re-enter the password.")
password2 = Console.ReadLine()
Loop Until password2 = password1
password = password1
Console.WriteLine("your password has been created.")
Console.ReadLine()
The below code generates the file
Dim fileName = "C:\Users\emily\Documents\Details.csv"
Dim fileAppend As New System.IO.StreamWriter(fileName, True)
fileAppend.WriteLine(name & ", " & age & ", " & username & ", " & password & ", " & yeargroup)
fileAppend.Close()
So basically I have details about the users stored in a csv file. The columns are arranged as follows: name, age, username, password, yeargroup. I need to be able to input a username and for it to be found in the array/list and then input the password and if the password doesn't match for it to start again.
Nice homework. You should think about storing password. Clear text is obviously risky. With the user file load in a table like this will let you manage all of the user. Add,Remove, Change then just save over the userfile.
Public Class Form1
Dim UserTable As New DataTable("UserTable")
Dim SomeUserName As String = "slims"
Dim SomePassword As String = "abc1234!"
Sub ReadUserFile()
Dim fileName = "C:\dump\test.csv"
Dim fileReader As New System.IO.StreamReader(fileName)
UserTable.Columns.Add("Name")
UserTable.Columns.Add("Age")
UserTable.Columns.Add("Username")
UserTable.Columns.Add("Password")
UserTable.Columns.Add("YearGroup")
Do Until fileReader.EndOfStream = True
Dim OneLine As String = fileReader.ReadLine()
UserTable.Rows.Add(OneLine.Split(","))
Loop
fileReader.Close()
End Sub
Sub WriteUserFile()
Dim fileName = "C:\dump\test.csv"
Dim fileWriter As New System.IO.StreamWriter(fileName)
For Each xRow As DataRow In UserTable.Rows
fileWriter.WriteLine(String.Format("{0},{1},{2},{3},{4}", xRow("Name"), xRow("Age"), xRow("Username"), xRow("Password"), xRow("YearGroup")))
Next
fileWriter.Close()
End Sub
Function CheckUserPassword(UserName As String, Password As String) As Boolean
Dim Found As Boolean = False
For Each xRow As DataRow In UserTable.Rows
If (xRow("Username") = SomeUserName) And (xRow("Password") = SomePassword) Then
Found = True
Exit For
Else
Found = False
End If
Next
Return Found
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReadUserFile()
If CheckUserPassword(SomeUserName, SomePassword) = True Then
'Good to go
Else
'bad user/pass
End If
WriteUserFile()
End Sub
End Class
You can use IO.File.ReadAllLines(fileName) to read the lines into an array of strings. Then you can use String.Split() on each line to split the fields and pick out the username and password.
dim allLines as String() = IO.File.ReadAllLines(fileName)
for each line as String in allLines
dim lineArray() as string
lineArray = line.Split(New Char() {","c})
username = lineArray(2)
password = lineArray(3)
if username = theUsernameYouWant then
'Found the user. Now check their password
endif
next
I havn't tested this code. Might have syntax errors.

Setting Static IP Address VB.net

I am writing a script for setting static ip to computers. it reads a file that has mac addr - ip addr pair. based on the computers mac address it gets its ip address from the file. I have problem setting this up. I have never done any kind of .net programming. I wrote a bashscript for linux side which works, but for windows I don't have any experience. I wrote the program in vb.net. Until now the program can get the data from the file, now I have to set static ip based on the mac address and also hostname. there were several different posts 1, 2, but they were all in c# ,and have problem converting them to VB.Net. It would be great if someone could provide a pointer on how to Set Static IP address for a specific NIC on local computer.
Imports System
Imports System.Text.RegularExpressions
Imports System.Net.NetworkInformation
Imports System.IO
Imports System.Management
Module Module1
Const FAILURE = 1
Const SUCCESS = 0
Dim phyAddr As String = getMAC()
Sub Main()
Dim arguments(3) As String
Dim fileName As String = ""
If Environment.GetCommandLineArgs.Count = 3 Then
arguments = Environment.GetCommandLineArgs
fileName = arguments(2)
Else
Console.WriteLine("Wrong Syntax!")
help()
Console.Read()
close(FAILURE)
End If
If validName(fileName) Then
If fileExists(fileName) Then
'search file for ip
Dim confData As String = searchFile(phyAddr, fileName)
If Not String.IsNullOrEmpty(confData) Then
Dim netConf() As String = splitLine(confData)
Dim hostName As String = netConf(1)
Dim ipAddr As String = netConf(2)
Dim netMask As String = netConf(3)
Dim gateway As String = netConf(4)
Dim dns1 As String = netConf(5)
Dim dns2 As String = netConf(6)
Else
Console.WriteLine("Couldn't find MAC {0} in file {1}", phyAddr, fileName)
Console.Read()
close(FAILURE)
End If
Else
Console.WriteLine("File {0} doesn't exist", fileName)
Console.WriteLine("Please provide an absolute path to file")
Console.Read()
close(FAILURE)
End If
Else
Console.WriteLine("File name {0} not recognized", fileName)
Console.Read()
close(FAILURE)
End If
End Sub
Private Sub help()
Console.WriteLine("Please call program as: ")
Console.WriteLine("networkconfiguration -f datafile")
End Sub
Private Sub close(exitCode As Integer)
Environment.Exit(exitCode)
End Sub
Private Function validName(name As String) As Boolean
Static fileNameExpression As New Regex("^[\\:_a-zA-Z0-9.]+")
Return fileNameExpression.IsMatch(name)
End Function
Private Function fileExists(name As String) As Boolean
Return My.Computer.FileSystem.FileExists(name)
End Function
Private Function getMAC() As String
Dim nic As NetworkInterface
Dim result As String = String.Empty
For Each nic In NetworkInterface.GetAllNetworkInterfaces()
If nic.Name.Contains("Ethernet0") Then
result = nic.GetPhysicalAddress.ToString
Exit For
End If
Next
Return result
End Function
Private Function searchFile(keyword As String, fileName As String) As String
'store result
Dim result As String = String.Empty
'search for keyword in returned data
Using reader As New StreamReader(fileName)
While Not reader.EndOfStream
Dim line As String = reader.ReadLine
If line.Contains(keyword) Then
result = line
Exit While
End If
End While
End Using
Return result
End Function
Private Function splitLine(line As String) As String()
Dim separator As Char = ";"
Return line.Split(separator)
End Function
Private Function setupNetwork(ipAddr As String, netmask As String, gateway As String, dns1 As String, dns2 As String) As Boolean
Dim mc As New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim moc As New ManagementObjectCollection
Dim mo As ManagementObject
moc = mc.GetInstances()
For Each mo In moc
'make sure this is ipenabled device
'not something like memory card or VMWare
Next
End Function
End Module
Ok solved it. I will just post my answer here so others might benefit.
' set the network configuration of a computer
Function setupNetwork(phyAddr As String, ipAddr As String, netmask As String, gateway As String, dns1 As String, dns2 As String) As Boolean
Dim result As Boolean = False
' concatenate two dns addresses into one
Dim dnsSearchOrder As String = dns1 + "," + dns2
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
For Each objMO As ManagementObject In objMOC
If (CBool(objMO("IPEnabled"))) Then
' remove colons from mac address so that it could match the
' provided mac address
Dim origMAC As String = objMO("MacAddress").ToString()
Dim pattern As String = ":"
Dim replacement As String = ""
Dim rgx As New Regex(pattern)
' the mac address with colons removed from it
Dim repMAC As String = rgx.Replace(origMAC, replacement)
If (String.Equals(phyAddr, repMAC)) Then
Try
Dim objNewIP As ManagementBaseObject = Nothing
Dim objNewGate As ManagementBaseObject = Nothing
Dim objNewDNS As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableStatic")
objNewGate = objMO.GetMethodParameters("SetGateways")
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder")
'set defaultgateway
objNewGate("DefaultIPGateway") = New String() {gateway}
objNewGate("GatewayCostMetric") = New Integer() {1}
'set ipaddress and subnetmask
objNewIP("IPAddress") = New String() {ipAddr}
objNewIP("SubnetMask") = New String() {netmask}
objNewDNS("DNSServerSearchOrder") = dnsSearchOrder.Split(",")
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, Nothing)
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, Nothing)
objSetIP = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDNS, Nothing)
result = True
Exit For
Catch ex As Exception
Console.WriteLine("Couldn't Set IP Address!")
Console.Read()
close(FAILURE)
End Try
End If
End If
Next
Return result
End Function
'set computers host name
Private Function setHostname(hostname As String) As Boolean
Dim result As Boolean = False
Dim path As New ManagementPath
path.Server = System.Net.Dns.GetHostName
path.NamespacePath = "root\CIMV2"
path.RelativePath = "Win32_Computersystem.Name='" & path.Server & "'"
Dim objMO As New ManagementObject(path)
Dim params() As Object = {hostname}
objMO.InvokeMethod("Rename", params)
result = True
Return result
End Function

For each ip try a list of urls

Now i have:
Dim i As Integer
Dim web As New WebClient With {.Proxy = Nothing}
'http://1.2.3.4/sql.db
Dim attkstring As String = "/sql.db"
i = 0
Dim shellx As Integer = 0
Dim sUrl As String = shells.Items(shellx) & attkstring
For Each item In shells.Items
Try
If web.OpenRead(sUrl) = True Then
End If
Catch ex As Exception
End Try
shellsloadedtext.Items.Add(sUrl)
shellx += 1
Next
But in my ListBox write all (ip+url), I need to write the IP + the URL just in case work, and now writes them even if there are no
Ex: real ip: 7.7.7.7 false ip: 1.1.1.1
I write in the ip list 7.7.7.7 1.1.1.1
And my ListBox shellsloadedtext wirte 7.7.7.7/sql.db and 1.1.1.1/sql.db
Help me
Does this help?
Dim sUrl As String = ips.Items(urlchk) & urlstring
web.DownloadString(sUrl)
yourListBox.Items.Add(sUrl)
Reference:
HTTP GET with .NET WebClient

Grabbing values sent to a console application in VB.net

What I'm trying to accomplish I have a textbox control and a button control on a form. When clicked whatever is entered into the textbox control, I want to send that data to a console application, which in turn create a text file. I have it mostly working but I can't get the data sent from the web application. How do I accomplish this? Here is what I have so far.
Here is my sub to send to the console application:
Public Sub send_to_console()
Dim file As String = "C:\inetpub\wwwroot\TestConsoleApp\TestConsoleApp\bin\Debug\TestConsoleApp.exe"
Dim info As ProcessStartInfo = New ProcessStartInfo(file, TextBox1.Text)
Dim p As Process = Process.Start(info)
End Sub
Console App Code:
ublic Sub Main(ByVal args As String)
Dim w As StreamWriter
Dim filepath As String = "C:\xml_files\testFile.txt"
Dim new_string As String
new_string = "This has been completed on " & Date.Now
If args = "" Then
new_string = "No data entered on: " & Date.Now
Else
new_string = args & " " & Date.Now
End If
If System.IO.File.Exists(filepath) Then
File.Delete(filepath)
End If
w = File.CreateText(filepath)
w.WriteLine(new_string)
w.Flush()
w.Close()
End Sub
Currently i'm getting an error: no accessible Main
'#######################EDITS###########
Dim file As String = "C:\inetpub\wwwroot\TestConsoleApp\TestConsoleApp\bin\Debug\TestConsoleApp.exe"
Dim info As ProcessStartInfo = New ProcessStartInfo(file, TextBox1.Text)
info.UseShellExecute = False
Dim p As Process = Process.Start(info)
main takes an array of string not a string.
so
Public Sub Main(ByVal args As String())
.....
If args.length < 1 Then
new_string = "No data entered on: " & Date.Now
Else
new_string = args(0) & " " & Date.Now
End If
.....
End Sub
In order to prevent windows from splitting your arguments concatenate a quote character before and after
Dim info As ProcessStartInfo = New ProcessStartInfo(file, """" & TextBox1.Text & """")
Four double quote characters represent a string literal containing a single double quote.