How can I make a SSH tunnel command into a service on Windows 10? - service

I have a very simple command in powershell to start SSH tunnels:
ssh -N -L 28777:localhost:28778 myapp-db
What's the simplest way to make this a service, so I can run:
start-service db-tunnel
etc on Windows 10? I've read an old article on doing this and it involves using C#, which seems way too complex for such a simple task.

PowerShell is not necessary. Here's one way:
Install the Windows Server 2003 Resource Kit Tools package somewhere and get the files instsrv.exe and srvany.exe.
Use srvany.exe to create the service using the ssh.exe program and its parameters using the information in Microsoft help article 137890.
For example:
instsrv "SSH Server" "C:\Program Files (x86)\Resource Kit Tools\srvany.exe"
Of course, specify whatever service name you want and the path and filename of srvany.exe.
Next, use the registry editor to go to HKLM\SYSTEM\CurrentControlSet\Services\SSH Tunnel (or whatever you named the service) in the registry and create a Parameters subkey. In the Parameters subkey create an Application value (REG_SZ type):
C:\Program Files (x86)\ssh\ssh.exe
(or whatever - the path and filename to your ssh executable).
You can also create the values AppDirectory (REG_SZ) to specify the starting directory for the executable, and AppParameters (REG_SZ) to specify the parameters to the executable; e.g.:
-N -L 28777:localhost:28778 myapp-db
You can substitute the use of the NSSM tool mentioned by BenH in his comment if you prefer that tool and are allowed to use third-party software.

To make something into a service, you would need to compile your script into an executable. This can be done via PS2EXE.
What may work just as well for you is making a function in powershell, Start-DbTunnel, and making that import into your powershell session on start. You can do this by loading functions in the foloowing path:
$PSprofilePath\Microsoft.PowerShell_profile.ps1
or for the ISE
$PSprofilePath\Microsoft.PowerShellISE_profile.ps1
Inside those files, I have
$PSprofilePath = "C:\Users\cknutson\Documents\WindowsPowershell"
$items = Get-ChildItem "$PSprofilePath\functions"
#Set-Location "$PSprofilePath\functions"
$items | ForEach-Object {
. $_.FullName
}
Set-Location C:\
Any scripts containing functions, or otherwise will be run each time you open a powershell host.

Related

PowerShell SCript to Execute CMD.exe with Arguments

SO I have surfed this site and the web and I feel as though I am missing something simple.
I find related questions but none that combine a scriptblock and remote calling of a 3rd party app (not a simply windows function or app)
I have the following string that I can copy into a command window and run without issue
"C:\Program Files (x86)\Vizient\Vizient Secure Channel v2.1\VizientSC.exe" UID=me#musc.edu PWD=XXXXXXXXX HCOID=123456 PRODTYPE=PRO-UHCSECURECHANNEL-CDB PACKAGETYPE=OTH FOLDERPATH="\\da\db5\MyFiles\Viz\20180413"
To simplify this, lets just assume I want to run this same String every time BUT with a REMOTE call.
I have written this many different ways but to no avail using
Invoke-Command -ComputerName "edwsql" -ScriptBlock { .........
I simply want to run the designated string using cmd.exe on a remote machine.
The EXE being run in the string is a 3rd party software that I do not want to install all all possible locations. Much simpler to run remote form the box it is already installed and is secure.
Can someone point me in the right direction???? Pls???? I'm new to PowerShell. I am trying to phase out some old PERL as the folks who can support that on the client site are few and far between these days.
You don't need to try so hard. PowerShell can run commands. If the command you want to run contains spaces, enclose in " (as you have done) and invoke it with the & (call or invocation) operator. This is all you need to do:
& "C:\Program Files (x86)\Vizient\Vizient Secure Channel v2.1\VizientSC.exe" UID=me#musc.edu PWD=XXXXXXXXX HCOID=123456 PRODTYPE=PRO-UHCSECURECHANNEL-CDB PACKAGETYPE=OTH FOLDERPATH="\\da\db5\MyFiles\Viz\20180413"
If a parameter on the executable's command line contains any characters that PowerShell interprets in a special way, you will need to quote it.

Is it possible to stop Julia from using Powershell on Windows 7?

My company uses CYCLANCE and CYCLANCEProtect is preventing me to run Pkg.build(). Is it possible to stop Julia from using Powershell on Windows 7 and use cmd instead?
Here is an example:
julia> Pkg.build("Gumbo")
INFO: Building Gumbo
CylancePROTECT Script Control has blocked access to this PowerShell script.
CylancePROTECT Script Control has blocked access to this PowerShell script.
====================================================[ ERROR: Gumbo ]=======
You could try to use cURL for downloading which is also available on windows (here are some installation instructions). Julia allows to override the download function by defining a function with the same name:
function Base.download(url::AbstractString, filename::AbstractString)
run(`curl -L -f -o $filename $url`)
filename
end
Once you paste this code in the julia REPL, julia should use this cURL download function (instead of PowerShell). If you want to make this permanent you can put this code in a file called .juliarc.jl (in the home directory, i.e. the output of homedir()).

Calling External Command From Powershell Plugin

I have an application process that runs in IBM UrbanCode. The process uses a Powershell Script that uses the CloudFoundry CLI. Our application process runs on an agent on which the CloudFoundry CLI is installed and available on the Path. Strangely enough, the Powershell plugin doesn't know that the CloudFoundry CLI is on the path. Echoing out the path via the plugin itself confirms this.
Currently, our application process looks like:
Copy CloudFoundry CLI into UCD's workspace at the start of the job.
Execute various CloudFoundry commands via the following sytax: .\cf login -u foo -p bar -o baz -s bart
I want to avoid copying the client into the workspace and having to use the .\cf sytax in order to make the scripts more portable.
How can I get the Powershell plugin to respect the Agent's path?
Sounds like the user that your powershell agent is running under does not have CloudFoundry in its path. options are
1. Ensure the PATH variable is set system wide.
2. instead of copying the CloudFoundary CLI you could manually add the path to CloudFoundry before you run the script
$env:Path += ;<PATH TO CLOUDFOUNARY>
Note: this will only persist for the current session.
To test that you have CloudFoundary in the path you can use
Get-Command cf

Azure Cloud Service Startup task that needs to run a PowerShell script

All,
Note: I have updated the question after some feedback.
Thanks to #jisaak for his help so far.
I have the need to run a PowerShell script that adds TCP bindings and some other stuff when I deploy my Cloud Service.
Here is my Cloud Service Project:
Here is my Cloud Service Project and Webrole project:
Here is my task in ServiceDefinition.csdef:
And here is the PowerShell script I want to run:
here is my attempt at the Startup.cmd:
When I deploy I get this in the Azure log:
And this in the powershell log:
Any help would be very much appreciated.
I think I am nearly there but following other people syntax on the web doesn't seem to get me there.
thanks
Russ
I think the issue is that the working directory of the batch command interpreter when it runs Startup.cmd runs is not as expected.
The Startup.cmd is located in the \approot\bin\Startup directory but the working directory is \approot\bin.
Therefore the command .\RoleStartup.ps1 is not able to find the RoleStartup.ps1 as it is looking in the bin directory not in the bin\Startup directory.
Solutions I know to this are:
Solution 1:
Use ..\Startup\RoleStartup.ps1 to call the RoleStartup.ps1 from Startup.cmd.
Soltuion 2:
Change the current working directory in Startup.cmd so that the relative path .\RoleStartup.ps1 is found. I do this by CHDIR %~dp0 (see here) to change into the directory that contains Startup.cmd.
Solution 3:
As Don Lockhart's answer suggested, do not copy the Startup directory to the output, instead leave it set as "Content" in the Visual Studio project. This means the files within it will exist in the \approot\Startup directory on the Azure instance. (You would then want to make sure that the Startup folder is not publically accessible via IIS!). Then update the reference to Startup.cmd in ServiceDefinition.csdef to ..\Startup\Startup.cmd, and update the reference to RoleStartup.ps1 in Startup.cmd to ..\Startup\RoleStartup.ps1. This works on the fact that the working directory is bin and uses ..\Startup to always locate the Startup directory relative to it.
You don't need to set the executionpolicy within your cmd - just call the script. Also, you should use a relative path because you can't rely that there is C disk.
Change your batch to:
powershell -executionpolicy unrestricted -file .\RoleStartup.ps1
Right click on the RoleStartup.ps1 and Startup.cmdin Visual Studio and ensure that the Copy to Output directory is set to copy always.
If this still doesn't work, remove the startup call in your csdef, deploy the service, rdp into it and try to invoke the script by yourself to retrieve any errors.
Edit:
Try to adopt your script as below:
Import-Module WebAdministration
$site = $null
do # gets the first website until the result is not $null
{
$site = Get-WebSite | select -first 1
Sleep 1
}
until ($site)
# get the appcmd path
$appcmd = Join-Path ([System.Environment]::GetFolderPath('System')) 'inetsrv\appcmd.exe'
# ensure the appcmd.exe is present
if (-not (Test-Path $appcmd))
{
throw "appcmd.exe not found in '$appcmd'"
}
# The rest of your script ....
I've found it easier in the past to not copy the content to the output directory. I have approot\bin as the working directory. My startUp task element's commandLine attribute uses a relative reference to the .cmd file like so:
The .cmd file references the PowerShell script relatively from the working directory as well:
PowerShell -ExecutionPolicy Unrestricted -f ..\StartUp\RoleStartup.ps1
Ok,
So I am coming back to this after many different attempts to make it work.
I have tried using:
Startup config in the ServiceDefinition.csdef
I have tried registering a scheduled task on the server that scans the Windows Azure log looking for [System[Provider[#Name='Windows Azure Runtime 2.6.0.0'] and EventID=10004]]
Nothing worked either due to security or the timing of events and IIS not being fully setup yet.
So I finally bit the bullet and used my Webrole.cs => public override bool OnStart() method:
Combined with this in the ServiceDefinition.csdef:
Now it all works. This was not the most satisfying result as some of the other ways to do it felt more elegant. Also, many others posted that they got the other ways of doing it to work. Maybe I would have got there eventually but my time was restricted.
thanks
Russ

Is there a SCP alternative for PowerShell?

I need to write a script that transfers files from a folder onto another server (Linux), but the script that's transferring files is on windows, and I was wondering if there was an alternative to scp for PowerShell (or if there was another way of doing this)
There is a handy little tool that comes with Putty called pscp.exe that will do this and can be called in powershell easily.
Example below copies from windows to a CentOS box (logging in as the usercode "bill") and you use the -pw switch in pscp to pass in a password (otherwise the command window that is spawned will prompt for the Linux password):
Start-Process 'C:\Program Files (x86)\PuTTY\pscp.exe' -ArgumentList ("-scp -pw password C:\Document.rtf bill#192.168.0.28:/home/bill/")
PuTTY Secure Copy client
Release 0.62
Usage: pscp [options] [user#]host:source target
pscp [options] source [source...] [user#]host:target
pscp [options] -ls [user#]host:filespec
Options:
-V print version information and exit
-pgpfp print PGP key fingerprints and exit
-p preserve file attributes
-q quiet, don't show statistics
-r copy directories recursively
-v show verbose messages
-load sessname Load settings from saved session
-P port connect to specified port
-l user connect with specified username
-pw passw login with specified password
-1 -2 force use of particular SSH protocol version
-4 -6 force use of IPv4 or IPv6
-C enable compression
-i key private key file for authentication
-noagent disable use of Pageant
-agent enable use of Pageant
-batch disable all interactive prompts
-unsafe allow server-side wildcards (DANGEROUS)
-sftp force use of SFTP protocol
-scp force use of SCP protocol
pscp.exe is a viable option, but I have been using a library from Rebex for a couple years now for SFTP and FTPS transfers in both C# apps and PowerShell scripts with great success. Their package also includes an SCP object but I haven't personally used it.
It does cost money vs. pscp being free. Before selecting the Rebex package, I had considered going the PuTTY route but my team decided that having a library we could easily roll into any app/script was worthwhile in the long term.
You can use WinSCP .NET assembly from PowerShell for SCP transfers.
For example see http://winscp.net/eng/docs/library_powershell#example
The example uses SFTP protocol. To use SCP, just modify it to:
$sessionOptions.Protocol = [WinSCP.Protocol]::Scp
Though if your server support SCP protocol, it's likely it also supports SFTP. SFTP is better choice, if you have the option.
Why use an alternative to SCP when you can use SCP?
Windows has OpenSSH (which includes SCP) as an optional component these days, so you could just use that. It first appeared in the Autumn 2018 version of Windows 10. It's nearly identical to the command you find in most Linux distributions, as it's derived from the same code base. Microsoft just made one or two minor tweaks to make it work on windows.
It is simple to install just go to Start->Settings->Apps->Optional Features->View Features enter in OpenSSH in the search box and check the OpenSSH client and click next. See OpenSSH in Windows for more detailed instructions on how to set it up. For a more PowerShell way of installing it run this from an elevated PowerShell prompt:
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
You can use this command to check if there is a newer version and whether you already have it installed:
Get-WindowsCapability -Online | Where Name -Like '*ssh*'
Once installed, you call scp from PowerShell just like you would any other executable command.
scp file.dat user.name#example.com:/target/path
If you really don't want to use SCP use Copy-Item
This requires PowerShell to be installed on your server. Yes you can install PowerShell on Linux. Just call Copy-Item with the -ToSession parameter passed an SSH connected session, I've never actually tried it though. It requires a recent version of PowerShell and some setting up see PowerShell remoting over SSH. Something like this:
Copy-Item C:\localPath\*.* ~\remotePath\ -ToSession (New-PSSession -HostName UserA#LinuxServer01:22 -KeyFilePath c:\\userAKey_rsa)
If both machines are Windows machines you can use the same -ToSession parameter to copy files over WinRM. But both machines have to be domain joined or there is the possibility of security issues.
There is also a ".NET friendly" way:
you can use the SharpSSH dll to execute ssh commands, and do scp/sftp tranfers.
For example:
[Reflection.Assembly]::LoadFrom((Resolve-Path .\Tamir.SharpSSH.dll))
$ssh = New-Object Tamir.SharpSsh.Sftp("server","user","password")
$ssh.Connect()
$ssh.Put("C:\localfile","distantfile")
$ssh.Close()
There is the SSH.Net library, too, it does approximatively the same things.