PuTTY in C# for file transfer - putty

Can any one help me with a code snippet in C# for transferring a file on my local machine to a remote server using PSCP (PuTTY) transfer methodology? I would really appreciate the help.
Thanks

You can use a library that support SCP like SSHNet or WinSCP. Both provide samples and tests that demonstrate how they work.
With SSH.Net you can upload a file using this code (from the test files):
using (var scp = new ScpClient(host, username, password))
{
scp.Connect();
scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
scp.Disconnect();
}
With the WinSCP library the code looks like this (from the samples):
SessionOptions sessionOptions = new SessionOptions {
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
SshHostKey = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult = session.PutFiles(#"d:\toupload\*", "/home/user/", false, transferOptions);
// Throw on any error
transferResult.Check();
}

Using SFTP and SCP supported clients with .NET Libraries might be the best option. But here is a simple way to use PSCP:
Process cmd = new Process();
cmd.StartInfo.FileName = #"C:\PuTTY\pscp.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
string argument = #"-pw pass C:\testfile.txt user#10.10.10.10:/home/usr";
cmd.StartInfo.Arguments = argument;
cmd.Start();
cmd.StandardInput.WriteLine("exit");
string output = cmd.StandardOutput.ReadToEnd();

Related

terraform windows server 2016 in Azure and domain join issue logging in to domain with network level authentication error message

I successfully got a windows server 2016 to come up and join the domain. However, when I go to remote desktop login it throws an error about network level authentication. Something about domain controller cannot be contacted to perform Network Level Authentication (NLA).
I saw some video on work arounds at https://www.bing.com/videos/search?q=requires+network+level+authentication+error&docid=608000415751557665&mid=8CE580438CBAEAC747AC8CE580438CBAEAC747AC&view=detail&FORM=VIRE.
Is there a way to address this with terraform and up front instead?
To join domain I am using:
name = "domjoin"
virtual_machine_id = azurerm_windows_virtual_machine.vm_windows_vm.id
publisher = "Microsoft.Compute"
type = "JsonADDomainExtension"
type_handler_version = "1.3"
settings = <<SETTINGS
{
"Name": "mydomain.com",
"User": "mydomain.com\\myuser",
"Restart": "true",
"Options": "3"
}
SETTINGS
protected_settings = <<PROTECTED_SETTINGS
{
"Password": "${var.admin_password}"
}
PROTECTED_SETTINGS
depends_on = [ azurerm_windows_virtual_machine.vm_windows_vm ]
Is there an option I should add in this domjoin code perhaps?
I can log in with my local admin account just fine. I see the server is connected to the domain. A nslookup on the domain shows an ip address that was configured to be reachable by firewall rules, so it can reach the domain controller.
Seems like there might be some settings that could help out, see here, possibly all that is needed might be:
"EnableCredSspSupport": "true" inside your domjoin settings block.
You might also need to do something with the registry on the server side, which can be done by using remote-exec.
For example something like:
resource "azurerm_windows_virtual_machine" "example" {
name = "example-vm"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
network_interface_ids = [azurerm_network_interface.example.id]
vm_size = "Standard_DS1_v2"
storage_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2019-Datacenter"
version = "latest"
}
storage_os_disk {
name = "example-os-disk"
caching = "ReadWrite"
create_option = "FromImage"
managed_disk_type = "Standard_LRS"
}
os_profile {
computer_name = "example-vm"
admin_username = "adminuser"
admin_password = "SuperSecurePassword1234!"
}
os_profile_windows_config {
provision_vm_agent = true
}
provisioner "remote-exec" {
inline = [
"echo Updating Windows...",
"powershell.exe -Command \"& {Get-WindowsUpdate -Install}\"",
"echo Done updating Windows."
]
connection {
type = "winrm"
user = "adminuser"
password = "SuperSecurePassword1234!"
timeout = "30m"
}
}
}
In order to set the correct keys in the registry you might need something like this inside the remote-exec block (I have not validated this code) :
Set-ItemProperty -Path 'HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-tcp' -Name 'SecurityLayer' -Value 0
In order to make the Terraform config cleaner I would recommend using templates for the Powershell script, see here
Hope this helps

How we can replace AddDeveloperSigningCredential on AWS Serverless Lambda environment?

We are using Identity Server4 with EntityFrameworkCore and we have deployed our .NET Core application as a lambda function using aws toolkit ("https://aws.amazon.com/blogs/developer/preview-of-the-aws-toolkit-for-visual-studio-2017/"). So how we can replace AddDeveloperSigningCredential on aws serverless lambda environment?
Here is our ConfigurationServerices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
string connectionString = Configuration.GetConnectionString("IdentityServer");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddIdentityServer()
.AddDeveloperSigningCredential()
// this adds the config data from DB (clients, resources)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
}) // this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
// options.EnableTokenCleanup = true;
// options.TokenCleanupInterval = 30;
});
// Add S3 to the ASP.NET Core dependency injection framework.
services.AddAWSService<Amazon.S3.IAmazonS3>();
}
This is some example code that loads certs from the certificate store. If this is unavailable to you then you just need to serialise and persist the certificate(s) you need some other way but that ultimately yields a valid X509Certificate2 instance that you can pass into X509SecurityKey.
private static void ConfigureSigningCerts(IServiceCollection services)
{
var keys = new List<SecurityKey>();
var name = "MyCertName";
//The one that expires last at the top
var certs = X509.LocalMachine.My.SubjectDistinguishedName.Find("CN=" + name, false)
.Where(o => DateTime.UtcNow >= o.NotBefore)
.OrderByDescending(o => o.NotAfter);
if (!certs.Any()) throw new Exception("No valid certificates could be found.");
//Get first (in desc order of expiry) th
var signingCert = certs.FirstOrDefault();
if (signingCert == null) throw new InvalidOperationException("No valid signing certificate could be found.");
var signingCredential = new SigningCredentials(new X509SecurityKey(signingCert), "RS256");
services.AddSingleton<ISigningCredentialStore>(new DefaultSigningCredentialsStore(signingCredential));
foreach (var cert in certs)
{
var validationCredential = new SigningCredentials(new X509SecurityKey(cert), "RS256");
keys.Add(validationCredential.Key);
}
services.AddSingleton<IValidationKeysStore>(new DefaultValidationKeysStore(keys));
}
The constructor for X509Certificate2 can take a raw byte[] or a file path so you've got plenty of options when it comes to packaging and distributing the signing/validation certs.
To create a self signed certificate on windows you can use the command:
makecert -r -pe -n "CN=MyCertName" -b 01/01/2015 -e 01/01/2039 -eku 1.3.6.1.5.5.7.3.3 -sky signature -a sha256 -len 2048 mycert.cer
That creates a certificate named MyCertName in a file called mycert.cer.
Full docs for the tool here: https://msdn.microsoft.com/en-us/library/bfsktky3(VS.100).aspx

How to override endpoint in AWS-SDK-CPP to connect to minio server at localhost:9000

I tried something like:
Aws::Client::ClientConfiguration config;
config.endpointOverride = Aws::String("localhost:9000");
It does not work.
It seems that AWS-SDK-CPP by default uses virtual hosting:
https://bucket-name/s3.amazonaws.com
However, to access Minio, we need path style access:
https://localhost:9000/minio/bucket-name
In AWS-SDK-JAVA, there is:
AmazonS3ClientBuilder.withPathStyleAccessEnabled(true)
is there something similar in AWS-SDK-CPP?
The switch between path style and virtual hosting is in S3Client constructor:
S3Client(const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration(), bool signPayloads = false, bool useVirtualAdressing = true);
turn it off, as in:
Aws::Client::ClientConfiguration config;
config.endpointOverride = Aws::String("172.31.30.127:9000");
config.scheme = Aws::Http::Scheme::HTTP;
auto client = Aws::MakeShared<S3Client>("sample_s3_client", config, false, false);

Cannot connect to host -1016

Am new in kony. And am trying to connect webservice. Kindly check given below code.
var myhttpheaders={"Content-Type":"application/x-www-form-urlencoded"};`enter code here`
var email = myFrm.textbox212343550452827.text;`enter code here`
var pwd = myFrm.textbox212343550452828.text;`enter code here`
var inputParamTable = { "appID":"NewTestAsync",
"serviceID":"User",
"channel":"rc",
"emailID":email,
"Password":pwd,
httpheaders: myhttpheaders,
httpconfig:{timeout: 600, method: "post"} };
try
{
var connHandle = kony.net.invokeServiceAsync(//sample/middleware/MWServlet),inputParamTable, callbackfunction);
}
catch(err)
{
alert("Error"+err);
}
}
So my kony server is kony.net.invokeServiceAsync(//sample/middleware/MWServlet)throwing error like 1016 cannot connect to host.
Please any one help me for solve this issue.
Thanks&Regards,
Ramesh babu.K
inputParamTable, callbackfunctionFirstly, the right side of 'connHandle' statement is missing a "(".
Secondly the format for invoking a service call would be : kony.net.invokeServiceAsync (url,inputParamTable,callback,info)
You need to enter an actual URL like so :
var connHandle = kony.net.invokeServiceAsync("http://www.test.kony.com",
inputParamTable, callbackfunction);
So, Instead of //sample/middleware/MWServlet
try to give it like so :
kony.net.invokeServiceAsync("http://192.168.x.x:8080/middleware/MWServlet", inputParamTable, callbackfunction);
where you replace the 192.168.x.x:8080 with your local kony server IP.
So please check your parameters once again and try.

No connection could be made because the target machine actively refused it 127.0.0.1:8118

trying to create web request using Tor. getting this error - "Unable to connect to the remote server".
Tor default proxy - 8118.
i have goggled for it found solution for it using Tor as Proxy but it didn't worked for me.
Code-
Process p = new Process();
p.StartInfo = new ProcessStartInfo(#"C:\Users\king\Downloads\Tor Browser\App\tor.exe", "ControlPort 9151 CircuitBuildTimeout 10");
p.Start();
Thread.Sleep(5000);
Regex regex = new Regex("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", RegexOptions.Multiline);
do
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://whatismyipaddress.com/");
request.Headers.Add("Cache-Control", "max-age=0");
request.Proxy = new WebProxy("127.0.0.1:8118");
request.KeepAlive = false;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
string contenu = reader.ReadToEnd();
Console.WriteLine(regex.Match(contenu).Groups[0].Value);
}
}
Console.Write("en attente : continuez ?");
string line = Console.ReadLine();
if (line != "y")
break;
}
while (true);
p.Kill();
Console.ReadLine();
any idea what doing wrong in above code.
thank's
Just download the Privoxy here
the reason to run tor through privoxy is because c# does not work with socks proxies. and tor is a socks proxy, so it needs to be ran through a html proxy that runs through tor
Tor default proxy port is 8118. you have to first download privoxy here
To chain Privoxy and Tor, both running on the same system, you would use something like:
forward-socks5 / 127.0.0.1:9050
change its config to work with tor by uncommenting the above line
c# does not use sock proxies so that we have to run Tor and Provoxy at same. now you can send every web request using tor.

Resources