Calling SFTP process from VBA code - windows

problem - Store key in cache Question stop VBA app
I use pscp.exe in order to transfer files from windows to Linux machine.
Remark: pscp.exe exists in my VBA code (that client is part of the PuTTY tools)
When I copy files from my PC to any new Linux machines I get the question "Store key in cache? (y/n)" and this interrupts my VBA application (VBA application stopped on sftp process).
I need advice how to ignore the question "Store key in cache? (y/n)". Or maybe automatically sending a "y" key from my VBA code? Or other solution as defined in the PC registry before running the pscp.exe? But how to do that?
Example from WIN XP command line (cmd)
Remark: 192.9.200.120 (Linux server IP address)
"D:\documents and settings\udavid\pscp.exe" -sftp -l root -pw pass123
"D:\Documents and Settings\udavid\Desktop\scan_ip.ksh" 192.9.200.120:/var/tmp
CMD output :
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 1024 15:e1:ce:4f:8e:4e:7b:61:14:c3:df:3c:b1:50:67:b6
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)
Example of CMD output if I use -batch flag (pscp.exe -batch)
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 d5:80:49:7f:69:f1:29:7c:1f:99:ec:c9:f4:b2:6f:a0
Connection abandoned.
Lost connection
--- Example from my VBA code ---
Const cstrSftp As String = """D:\documents and settings\udavid\pscp.exe"""
Dim strCommand As String
Dim pUser As String
Dim pPass As String
Dim pHost As String
Dim pFile As String
Dim pRemotePath As String
pUser = "root"
pPass = "pass123"
pHost = "xxx.xxx.xxx.xxx" xxx.xxx.xxx.xxx - any server new IP
pFile = """D:\Documents and Settings\udavid\Desktop\scan_ip.ksh"""
pRemotePath = "/var/tmp"
strCommand = cstrSftp & " -sftp -l " & pUser & " -pw " & pPass & " " & pFile & " " & pHost & ":" & pRemotePath
Debug.Print strCommand
Shell strCommand, 1

You can use Shell "cmd /c echo y | " & strCommand, 1 as a suggested quick hack.
I use a home-made cExec class to pipe output and to selectively respond to putty warnings like this
With New cExec
.Run "d:\downloads\pscp.exe", sParams, True
Do While Not .AtEndOfOutput
If InStr(.ReadLineOutput, "(y/n)") Then
.WriteInput "y"
End If
Loop
End With

Try this :
echo y|"C:\Program Files\PuTTY\pscp.exe" -sftp -l root -pw pass123 C:\scan_ip.ksh $server:/var/tmp
It will "press" y to your program standar input.

The help (pscp /?) gives you the answer.
You should pass -batch to disable all prompts like that.
You may also want to quote your parameters correctly so spaces and quotes in the values don't break things.

Related

how to post a file or stdout into a http server?

I would like to execute some command then send them into my web server for analysis.
somethink like :
wmic csproduct get | wget http://someserver/cgi-bin/hello.pl
Except that wget is not delivered out-of-the-box by Microsoft.
How can I make the same using stuff that are delivered with Windows 2000 and futher? Can vbscript do the job?
Since you executing some commands to get your information, may be it would be more native to use a command shell environment?
How about PowerShell?
(New-Object System.Net.WebClient).UploadString("http://someserver/cgi-bin/hello.pl", (Get-WMIObject Win32_BIOS) )
read about the UploadString() method here
If you still want to stick to a vbscript solution, here is a sample code which accepts a text from stdin and posts it to your server:
Dim inp, http_req
inp = inp & WScript.StdIn.ReadAll()
WScript.Echo "Input: " & inp
Set http_req = CreateObject("WinHTTP.WinHTTPRequest.5.1")
http_req.open "POST", "http://someserver/cgi-bin/hello.pl", false
http_req.setRequestHeader "Content-Type", "text/plain"
http_req.send inp
The minimum requirements seems to be Windows 2000 Professional with SP3 , i personnaly tested the script with Windows XP.

Is it possible to work on normal (not SFTP) FTP on Renci SSH.NET? - which client to use?

I am using Renci SSH.NET, but trying to test on a FTP (not SFTP site).
I did get this working with WinSCP - but cannot get it to work on Renci -
WinSCP allows me to set the protocol to either FTP or SFTP - I think this is the issue - I am prompted for
No suitable authentication method found to complete authentication (publickey,keyboard-interactive).
How do I turn off SFTP (and just use FTP) on Renci SSH.NET? I tried
Dim c As Renci.SshNet.SftpClient / ScpClient/ BaseClient / NetConfClient
here is code:
Private Sub LancerUpload()
Dim PWAuthMeth = New PasswordAuthenticationMethod(Login, Password)
Dim KIAuthMeth = New KeyboardInteractiveAuthenticationMethod(Login)
AddHandler KIAuthMeth.AuthenticationPrompt, AddressOf HandleKeyEvent
Dim ConnectionInfo As New ConnectionInfo(ServerName, 22, Login, PWAuthMeth, KIAuthMeth)
Dim SshClient1 As New SshClient(ConnectionInfo)
Try
SshClient1.Connect()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
MsgBox(SshClient1.IsConnected)
End Sub
Private Sub HandleKeyEvent(sender As Object, e As Renci.SshNet.Common.AuthenticationPromptEventArgs)
For Each prompt As Renci.SshNet.Common.AuthenticationPrompt In e.Prompts
If prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) <> -1 Then
prompt.Response = Password
End If
Next
End Sub
As the name says, the Renci SSH.NET library is an SSH library.
The FTP has nothing to do with the SSH nor the SFTP. Contrary to the SFTP, what in a subsystem of the SSH.
So no, you cannot use the Renci SSH.NET for the FTP protocol.
You may want to read Is "SFTP" and "FTP over SSL" a same thing? and Differences between SFTP and "FTP over SSH".

How to add a Local Printer using VBScript on Windows 7?

I have a Windows 7 64bit pc, I'm trying to add a Local Printer which automatically installs the driver and shares the printer once it is done.
The port is a Loopback IP Address (127.0.0.1) and it uses the Zebra (ZDesigner LP 2844) Driver. (Which you can get here: http://www.zebra.com/us/en/support-downloads/desktop/lp-2844.html )
My current script works great on XP but not so good on Windows 7. It comes up with the error
"Microsoft VBScript runtime error:ActiveX component can't create object: 'Port.Port.1' for my script AddPort.vbs
The following script is called AddPort.vbs
'ADDING:
dim oPort
dim oMaster
set oPort = CreateObject("Port.Port.1")
set oMaster = CreateObject("PrintMaster.PrintMaster.1")
wscript.echo "Adding port to local machine...."
'Indicate where to add the port. Double quotes ("" ) stand for the local computer, which is the default, or put "\\servername"
oPort.ServerName = ""
'The name of the port cannot be omitted.
oPort.PortName = "CustomPortName"
'The type of the port can be 1 (TCP RAW), 2 (TCP LPR), or 3 (standard local).
oPort.PortType = 3
'For TCP RAW ports. Default is 9100.
oPort.PortNumber = 9101
'Try adding the port.
oMaster.PortAdd oPort
'Test for the status.
If Err <> 0 then
wscript.echo "Error " & Err & " occurred while adding port"
End If
The Following script is called AddPrinter.vbs
This script shows the error "Microsoft VBScript runtime error:ActiveX component can't create object: PrintMaster.PrintMaster.1
' Adding a Printer
' The sample code in this section creates any required objects, adds a printer to a remote server, and configures some driver and port information.
dim oMaster
dim oPrinter
wscript.echo "Adding VirtualPrinter printer to local machine...."
'The following code creates the required PrintMaster and Printer objects.
set oMaster = CreateObject("PrintMaster.PrintMaster.1")
set oPrinter = CreateObject("Printer.Printer.1")
'The following code specifies the name of the computer where the printer will be added. To specify the local
'computer, either use empty quotes (“”) for the computer name, or do not use the following line of code. If
'ServerName is not set, the local computer is used. Always precede the name of a remote computer with two backslashes (\\).
oPrinter.ServerName = ""
'The following code assigns a name to the printer. The string is required and cannot be empty.
oPrinter.PrinterName = "VirtualPrinter"
'The following code specifies the printer driver to use. The string is required and cannot be empty.
oPrinter.DriverName = "ZDesigner LP 2844"
'The following code specifies the printer port to use. The string is required and cannot be empty.
oPrinter.PortName = "LoopBack"
'The following code specifies the location of the printer driver. This setting is optional, because by default
'the drivers are picked up from the driver cache directory.
'oPrinter.DriverPath = "c:\drivers"
'The following code specifies the location of the INF file. This setting is optional, because by default the INF
'file is picked up from the %windir%\inf\ntprint.inf directory.
'oPrinter.InfFile = "c:\winnt\inf\ntprint.inf"
oPrinter.PrintProcessor = "winprint"
'The following code adds the printer.
oMaster.PrinterAdd oPrinter
'The following code uses the Err object to determine whether the printer was added successfully.
if Err <> 0 then
wscript.echo "Error " & Err & " occurred while adding VirtualPrinter"
else
wscript.echo "Printer added successfully"
end if
' To configure other printer settings, such as comments, create a Printer object and then call PrintMaster's method PrinterSet.
wscript.echo "Configuring printer...."
oPrinter.Comment = "Virtual printer to capture labels"
oPrinter.ShareName = "VirtualPrinter"
oPrinter.Shared = true
oPrinter.Local = true
oMaster.PrinterSet oPrinter
if Err <> 0 then
wscript.echo "Error " & Err & " occurred while changing settings for VirtualPrinter"
end if
Is there any other way I can create a Local Printer, Set the Driver, Port Number and Port Name and Share Name and Print Processor using vbscript in Windows 7???
Thank you in advance, the best response will receive points.
This is just what you need, for Windows 7:
The seven printer utilities, shown later, are located in the C:\Windows\System32\Printing_Admin_Scripts\en-US folder, which is not listed in the path. Therefore, you must actually change to this folder in order to run the utilities. And, since these utilities are designed to be run from the command line, you need to launch them from a Command Prompt window and run them using Windows Script Host's command-line-based script host (Cscript.exe).
Windows 7's VBScript printing utilities
VBScript File | What it does
---------------------------------------------
Prncnfg.vbs | Printer configuration
Prndrvr.vbs | Printer driver configuration
Prnjobs.vbs | Print job monitoring
Prnmngr.vbs | Printer management
Prnport.vbs | Printer port management
Prnqctl.vbs | Printer queue management
Pubprn.vbs | Publish a printer to Active Directory
Hope this works for you
I found another way to automate adding the printer, first I created a batch file then I used the prnmngr.vbs which comes with Windows 7 to automatically add the printer for me. For this to work I already had the Zebra driver installed on the machine (but the concept would be the same for any other type of printer). Then I ran the batch file.
Following shows how I did it, I've added the batch file text here:
Name the file: AddPrinter.bat
rem first change the directory to the script location
cd %WINDIR%\System32\Printing_Admin_Scripts\en-US\
rem vbs script path: %WINDIR%\System32\Printing_Admin_Scripts\en-US\Prnmngr.vbs
rem first add the port, specify name of port, assign it an IP Address, specify the type and the Port.
cscript prnport.vbs -a -r "LoopBack" -h 127.0.0.1 -o raw -n 9100
cscript prnport.vbs -a -r "LoopBack_2" -h 127.0.0.1 -o raw -n 9101
pause
rem specify the name of the new printer, specify the driver, specify the port it will use.
cscript prnmngr.vbs -a -p "VirtualPrinter" -m "ZDesigner LP 2844" -r "LoopBack"
pause
cscript prnmngr.vbs -a -p "Zebra LP2844" -m "ZDesigner LP 2844" -r "USB0001"
rem cscript prnmngr.vbs -a -p "Zebra GK420d" -m "ZDesigner GK420d" -r "LPT1:"
rem cscript prnmngr.vbs -a -p "Zebra GC420d" -m "ZDesigner GC420d" -r "COM1:"
pause
NET STOP SPOOLER
NET START SPOOLER
pause
To customise this you can use these websites as a reference;
http://technet.microsoft.com/en-us/library/cc725868(v=ws.10).aspx
http://technet.microsoft.com/en-us/library/bb490974.aspx
http://blog.ogwatermelon.com/?p=3489
http://winadminnotes.wordpress.com/2010/02/19/how-to-manage-printers-and-printer-drivers-remotely-from-command-line/
http://technet.microsoft.com/en-us/library/cc754352(v=ws.10).aspx

Reset password for renamed Administrator account

I need to create a .VBS script to reset the Windows local administrator password on a large group of computers. My problem is that some of our sites have renamed the administrator account for security reasons. Does anyone have a script which changes the password of the administrator account based on the SID of the original Administrator account?
Using the fact that local admin's SID always ends with -500:
strComputer="." ' local computer by default
Set objUser=GetObject("WinNT://" & strComputer & "/" & GetAdminName & ",user")
objUser.SetPassword "New local admin password"
objUser.SetInfo
Function GetAdminName
'This function was written using information from Table J.1 from the Windows XP resource Kit
'http://www.microsoft.com/resources/documentation/Windows/XP/all/reskit/en-us/Default.asp?url=/resources/documentation/Windows/XP/all/reskit/en-us/prnc_sid_cids.asp
Set objNetwork = CreateObject("Wscript.Network") 'get the current computer name
objComputerName = objNetwork.ComputerName
Set objwmi = GetObject("winmgmts:{impersonationLevel=impersonate}!//" & objComputerName)
qry = "SELECT * FROM Win32_Account where Domain = '" & cstr(objComputerName) & "'"
'set query, making sure to only look at local computer
For Each Admin in objwmi.ExecQuery(qry)
if (left(admin.sid, 6) = "S-1-5-" and right(admin.sid,4) = "-500") then 'look for admin sid
GetAdminName = admin.name
end if
next
end Function
There's a tool floating around somewhere called LookupAccountName (with source!) that given the SID of the builtin adminitrator will give you its name.
You're probably going to end up writing C++ code to pull this one off reasonably well.
Like Joshua says, I don't think you can do this with windows scripting host only, you could use it download something and execute it:
A custom app that calls LookupAccountSid(S-1-5-domain-500 SID or enum admin group)+NetUserSetInfo to reset the password (Needs to run this as admin)
http://home.eunet.no/pnordahl/ntpasswd/ (Reset at boot)
Dump the SAM hashes and crack the password (Cain,John the Ripper,L0phtCrack etc)
#DmitryK's answer is good, and I didn't know any of that stuff. But I do know that this sort of thing is usually cleaner in PowerShell, so I ported it.
For example, the whole GetAdminName function can be written:
$adminName = (gwmi win32_account | ? { $.SID.StartsWith( 'S-1-5-' ) -and $.SID.EndsWith( '-500' ) }).Name
(Add the -ComputerName option to the gwmi call to do this on a server.)
The rest becomes:
$user = ([ADSI]"WinNT://$($env:COMPUTERNAME)/$adminName,User")
$user.SetPassword( 'xxx' )
$user.SetInfo()
(applying the appropriate computer name as needed, of course.)

How to set Authentication Methods in IIS programmatically

We are working on automating the deployment of some IIS applications. I've used cscript.exe inside a windows batch file to create the web app and such. There are however a few settings currently done by hand that I need to automate. Namely, if you look at the properties of an app, under Directory Structure -> Authentication and access control -> Edit, I need to uncheck Enable anonymous access and check Integrated Windows authentication.
Is there an easy way to do this from a windows batch file?
EDIT: I should clarify this is IIS 6.0, so appcmd is not available.
hope this helpes:
http://forums.iis.net/t/1159665.aspx
I answered a very similar question a wee while back. The example uses the asdutil.vbs tool which you can call from your batch file:
Setting NTAuthenticationProviders at an Application level in IIS 6 (Stack Overflow)
Updated:
Because you've already got a CScript script to create the website, you can just set the AuthFlags in the script:
'' Some values just as an example
iisNumber = 668
ipAddress = "172.16.3.200"
hostName = "myserver.com"
wwwfolder = "c:\mysites\www"
Dim serverBindings(1)
serverBindings(0) = ipAddress & ":80:www." & hostName
serverBindings(1) = ipAddress & ":80:" & hostName
'' Create server
Set w3svc = GetObject("IIS://localhost/w3svc")
Set newWebServer = w3svc.Create("IIsWebServer", iisNumber)
newWebServer.ServerBindings = serverBindings
newWebServer.ServerComment = "Server is: " & hostName
newWebServer.SetInfo
'' Create /root app
Set rootApp = newWebServer.Create("IIsWebVirtualDir", "ROOT")
rootApp.Path = wwwFolder
rootApp.AccessRead = true
rootApp.AccessScript = true
rootApp.AppCreate(True)
rootApp.AuthFlags = 4 '' <== Set AuthFlags here
rootApp.SetInfo
See Configure Windows Authentication (IIS 7):
appcmd set config /section:windowsAuthentication /enabled:true | false
For IIS 6 probably WMI is the alternative:
Creating Sites and Virtual Directories, and Setting Properties Using WMI
IIsWebServiceSetting (WMI)
AuthFlags
Dim sSitePath = "1" 'Set the site ID here
Set oSite = GetObject("IIS://localhost/" & sSitePath & "/root")
Select Case oSite.AuthFlags
Case 1
Wscript.Echo "Anonymous"
Case 2
Wscript.Echo "Basic"
Case 4
Wscript.Echo "NTLM"
Case 6
Wscript.Echo "MD5"
Case 64
Wscript.Echo "Passport"
End Select

Resources