i'm totally new to DotRas so please be patient.. I have a windows server 2012 R2 with "Route and remote access" configured. In this simple configuration there is a dialer connection to a vpn as you can see in the first picture..
So, if i click connect.. everything works fine and the status of the network interface changes from disconnected to connected.
Going to the event viewer this is what i got:
Events from RASCLIENT sourcelog:
Event 1:
CoId={A52088DC-5358-44D6-8B77-DA49516C3FBD}: The user SYSTEM has started dialing a VPN connection using a all-user connection profile named VpnAtlanta02. The connection settings are:
Dial-in User = c******s
VpnStrategy = PPTP
DataEncryption = Require
PrerequisiteEntry =
AutoLogon = No
UseRasCredentials = Yes
Authentication Type = MS-CHAPv2
Ipv4DefaultGateway = No
Ipv4AddressAssignment = By Server
Ipv4DNSServerAssignment = By Server
Ipv6DefaultGateway = Yes
Ipv6AddressAssignment = By Server
Ipv6DNSServerAssignment = By Server
IpDnsFlags =
IpNBTEnabled = No
UseFlags = Private Connection
ConnectOnWinlogon = No.
Event 2:
CoId={A52088DC-5358-44D6-8B77-DA49516C3FBD}: The user SYSTEM is trying to establish a link to the Remote Access Server for the connection named VpnAtlanta02 using the following device:
Server address/Phone Number = ***.***.***.***
Device = WAN Miniport (PPTP)
Port = VPN3-4
MediaType = VPN.
Event 3:
CoId={A52088DC-5358-44D6-8B77-DA49516C3FBD}: The user SYSTEM has successfully established a link to the Remote Access Server using the following device:
Server address/Phone Number = ***.***.***.***
Device = WAN Miniport (PPTP)
Port = VPN3-4
MediaType = VPN.
Event 4:
CoId={A52088DC-5358-44D6-8B77-DA49516C3FBD}: The link to the Remote Access Server has been established by user SYSTEM.
Event 5:
CoId={A52088DC-5358-44D6-8B77-DA49516C3FBD}: The user SYSTEM has dialed a connection named VpnAtlanta02 to the Remote Access Server which has successfully connected. The connection parameters are:
TunnelIpAddress = 172.20.0.19
TunnelIpv6Address = None
Dial-in User = c******s.
Now.. my goal is to get connected from a windows service
So here is my code (the essential part):
Dialer = new RasDialer();
Dialer.PhoneBookPath = "C:\\Windows\\System32\\ras\\Router.pbk";
Dialer.Timeout = 20 * 1000;
Dialer.HangUpPollingInterval = 20 * 1000;
Dialer.AllowUseStoredCredentials = false;
Dialer.AutoUpdateCredentials = RasUpdateCredential.None;
Dialer.EntryName = "VpnAtlanta02";
Dialer.Credentials = new System.Net.NetworkCredential("c******s", "*********");
Watcher = new RasConnectionWatcher();
Watcher.EnableRaisingEvents = true;
Watcher.Connected += Watcher_Connected;
Watcher.Disconnected += Watcher_Disconnected;
InfoLog("Begin connection");
Watcher.Handle = Dialer.Dial();
private void Watcher_Disconnected(object sender, RasConnectionEventArgs e)
{
InfoLog(e.Connection.EntryName + " is disconnected");
}
private void Watcher_Connected(object sender, RasConnectionEventArgs e)
{
InfoLog(e.Connection.EntryName + " is connected");
}
Sofar, no matter what... going to the event viewer looking for the RasClient event source, as expected i got 5 events logged. 1,2,3 and 4 are equal to the ones generated by the manual connection unfortunately the last (5) is:
CoId={E2814072-13C7-44CF-998A-A1160FDC86E3}: The user SYSTEM dialed a connection named VpnAtlanta02 which has failed. The error code returned on failure is 720.
Please consider that if you think at some wrong credentials or else.. i did a try with no credentials at all and as expected in that case i wasn't able to get event 4
Any ideas?
First thing first! This is not the answer to my question but... I think it could be helpful for anyone who's experienced the same trouble.
After a bunch of tries and even some attempts to debug using DotRas source code i didn't get any step forward, besides i'm not sure this can actually be done. I said that because trying with "rasdial" command from an administrator command prompt i've got the same result: failed with error code 720. That said i've got my solution using powershell.
There's 3 powerful cmdlets which are all i was looking for
- Get-VpnS2SInterface
- Connect-VpnS2SInterface
- Disconnect-VpnS2SInterface
So i just set 3 simple methods and now everything works like a charm
public Boolean IsConnected()
{
Boolean retVal = false;
using (PowerShell ps = PowerShell.Create())
{
ps.AddCommand("Get-VpnS2SInterface");
ps.AddParameter("Name", "VpnAtlanta02");
foreach (PSObject result in ps.Invoke())
{
retVal = ("" + result.Members["ConnectionState"].Value).ToLower() == "connected";
}
}
return retVal;
}
public void Connect()
{
using (PowerShell ps = PowerShell.Create())
{
ps.AddCommand("Connect-VpnS2SInterface");
ps.AddParameter("Name", "VpnAtlanta02");
ps.AddParameter("PassThru");
foreach (PSObject result in ps.Invoke())
{
String destination = "";
foreach (String s in result.Members["Destination"].Value as String[])
{
destination += "{" + s + "}";
}
Service1.InfoLog("Destination=" + destination + "\r\n" +
"ConnectionState=" + result.Members["ConnectionState"].Value + "\r\n");
}
}
}
public void Disconnect()
{
using (PowerShell ps = PowerShell.Create())
{
ps.AddCommand("Disconnect-VpnS2SInterface");
ps.AddParameter("Name", "VpnAtlanta02");
ps.AddParameter("Force");
ps.Invoke();
Service1.InfoLog("Nic: " + "VpnAtlanta02" + " is connected: " + IsConnected());
}
}
Related
I am trying to backup a database on a remote development server and send it to a network drive folder that is shared between mine and the development pc.
I have attached the function I'm calling and the error that I am getting too.
However when I run this using the Visual Studio Start button in the top it works perfectly fine (When running in admin mode)
Everyone keeps saying permissions but I dont understand how the permissions on my pc will be taken into account on the development server
public static string BackupDatabase(string DatabaseName)
{
String sqlServerLogin = Properties.Resources.Username;
String password = Properties.Resources.Password;
String remoteSvrName = Properties.Resources.DataSource;
// Authentication
ServerConnection srvConn2 = new ServerConnection(remoteSvrName);
srvConn2.LoginSecure = false;
srvConn2.Login = sqlServerLogin;
srvConn2.Password = password;
// Initialisation of the server object
Server srv = new Server(srvConn2);
Backup bk = new Backup();
bk.Action = BackupActionType.Database;
bk.BackupSetDescription = "Staging Transfer";
bk.BackupSetName = DatabaseName + " Backup";
bk.Database = DatabaseName;
// Declare a BackupDeviceItem by supplying the backup device file name in the constructor, and the type of device is a file.
BackupDeviceItem bdi = default(BackupDeviceItem);
string backupPath = Properties.Resources.DatabaseBackupPath + DatabaseName + DateTime.Now.ToString("ddMMyyyy") + ".bak";
if (File.Exists(backupPath))
{
File.Delete(backupPath);
}
bdi = new BackupDeviceItem(backupPath, DeviceType.File);
// Add the device to the Backup object.
bk.Devices.Add(bdi);
bk.Checksum = true;
bk.ContinueAfterError = true;
bk.Initialize = true;
// Set the Incremental property to False to specify that this is a full database backup.
bk.Incremental = false;
// Specify that the log must be truncated after the backup is complete.
bk.LogTruncation = BackupTruncateLogType.Truncate;
// Run SqlBackup to perform the full database backup on the instance of SQL Server.
bk.SqlBackup(srv);
bk.Wait();
return backupPath;
}
Is anyone able to advise me on this? It's driving me crazy!
private void backupDatabaseWorker_DoWork(object sender, DoWorkEventArgs e)
{
backupDatabaseWorker.WorkerReportsProgress = true;
Utilities util = new Utilities();
string database = util.GetDatabase(filePathSelected.Text);
string backupReturn = SQL.BackupDatabase(database);
backupPath = backupReturn;
MessageBox.Show(database);
MessageBox.Show(backupReturn);
}
The GetDatabase function works fine, that uses the web config to grab the database name that the site uses.
Any help would be greatly appreciated
Error
Failed to connect to server dev. at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
at Microsoft.SqlServer.Management.Common.ConnectionManager.PoolConnect()
at Microsoft.SqlServer.Management.Common.ConnectionManager.GetServerInformation()
at Microsoft.SqlServer.Management.Smo.ExecutionManager.GetServerVersion()
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.get_ServerVersion()
at Microsoft.SqlServer.Management.Smo.Backup.Script(Server targetServer)
at Microsoft.SqlServer.Management.Smo.Backup.SqlBackup(Server srv)
at Microsoft.SqlServer.Management.Smo.Backup.SqlBackup(Server srv)
at PCS_Lithium.SQL.BackupDatabase(String DatabaseName)
at PCS_Lithium.PushToStagingForm.backupDatabaseWorker_DoWork(Object sender, DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
Microsoft.SqlServer.SmoExtended
I'm creating a website and in it I'm giving a link where the user enters his/her Azure VM username and password and then I'm gonna go ahead and restart the machine IIS server.
So I'm writing a .NET Code for implementing the same but no luck yet. I'm not able to restart the IIS server for the remote machines, I have even looked for an alternative approach to achieve the same using Powershell but unable to do so.
I tried remotely restarting the IIS server using WMI and also created code for calling Powershell in .Net Core but I'm not able to achieve the same.
Can someone please help me with how to restart the IIS server remotely using C# code or .NET Core code?
As for this...
Share me the link wherein there is a PowerShell script that restarts
IIS on a remote server using the system credentials.
... a quick search using 'Restart IIS on remote machine'
... will give a list of articles in the topic, some from right here on StackOverflow, since this is not the first time this has been asked. So, your question can be considered a potential duplicate of the below.
Example(s):
about_Remote - PowerShell | Microsoft Docs
Restart IIS on remote machine
Some of the answers, not using PowerShell to do this from the above are:
# Simplest will be
iisreset <servername>
# Run command prompt as admin and execute the command.
# Example : If server name is SRVAPP then command will be iisreset SRVAPP
# You could use sc
sc \\RemoteServer stop iisadmin
sc \\RemoteServer start w3svc
# or SysInternals' psexec. The PsTools suite is useful for these scenarios.
psexec \\RemoteServer iisreset
PowerShell Remoting requires you to be in the local admin group on the target host. You cannot run PowerShell code as SYSTEM unless you are running a scheduled task, even then it is the scheduled task running as whatever credential it was set for and running any script in that task. To run PowerShell code as another user, you must know the username and password.
You can use PowerShell to set up a scheduled task to run. Just search for 'PowerShell scheduled task' for details.
I tried the below codes for restarting IIS remotely but it didn't work.
Method 1:
using System.Diagnostics;
using System.Management;
using System.IO;
using System.Security;
Process myProcess = new Process();
ProcessStartInfo remoteAdmin =
new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "iisreset.exe"));
remoteAdmin.Arguments = "/restart";
myProcess.StartInfo.Verb = "runas";
var s = new SecureString();
//s.AppendChar('g');
Console.WriteLine("Enter username:");
string userName = Console.ReadLine();
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Enter password:");
string password = Console.ReadLine();
Console.WriteLine(Environment.NewLine);
var securePasswordString = new SecureString();
// Use ToCharArray to convert string to array.
char[] array = password.ToCharArray();
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from the array.
securePasswordString.AppendChar(array[i]);
}
remoteAdmin.UserName = userName;
remoteAdmin.Password = securePasswordString;
remoteAdmin.Domain = "localhost";
myProcess.StartInfo = remoteAdmin;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.Start(); //---ERROR HERE
if (!myProcess.Start())
{
// That didn't work
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Process did not start!!!");
}
myProcess.WaitForExit();
var processExitCode = myProcess.ExitCode;
if (processExitCode == 0)
{
Console.WriteLine("The operation completed successfully.");
}
if (processExitCode != 0)
{
// That didn't work
if (processExitCode == 5)
{
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Access Denied");
}
}
Console.ReadKey();
Method 2:
ConnectionOptions conn = new ConnectionOptions();
conn.Impersonation = ImpersonationLevel.Impersonate;
conn.Username = #"Username";
conn.Password = "";
//ManagementScope theScope = new ManagementScope("\\\\" + txtServerName.Text + "\\root\\cimv2", conn);
theScope.Connect(); //---ERROR HERE
I tried the below code to run powershell script from C# code but I need the script which takes remote server admin credentials and restart the IIS.
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
static void RunPsScriptMethod2()
{
StringBuilder sb = new StringBuilder();
PowerShell psExec = PowerShell.Create();
psExec.AddCommand(#"C:\Users\d92495j\Desktop\test.ps1");
psExec.AddArgument(DateTime.Now);
Collection<PSObject> results;
Collection<ErrorRecord> errors;
results = psExec.Invoke();
errors = psExec.Streams.Error.ReadAll();
if (errors.Count > 0)
{
foreach (ErrorRecord error in errors)
{
sb.AppendLine(error.ToString());
}
}
else
{
foreach (PSObject result in results)
{
sb.AppendLine(result.ToString());
}
}
Console.WriteLine(sb.ToString());
}
I use the Microsoft.Management.Infrastructure namespace to connect to remote computers to get WMI information and it works. But when I try to connect to a non-domain PC it does not work. Can anyone pinpoint what I am doing wrong.
Here is the code:
string computer = "Computer_B";
string domain = "WORKGROUP";
string username = ".\\LocalAdminUserName";
string plaintextpassword;
Console.WriteLine("Enter password:");
plaintextpassword = Console.ReadLine();
SecureString securepassword = new SecureString();
foreach (char c in plaintextpassword)
{
securepassword.AppendChar(c);
}
CimCredential Credentials = new
CimCredential(PasswordAuthenticationMechanism.Default, domain,
username,securepassword);
WSManSessionOptions SessionOptions = new WSManSessionOptions();
SessionOptions.AddDestinationCredentials(Credentials);
CimSession Session = CimSession.Create(computer, SessionOptions);
var allVolumes = Session.QueryInstances(#"root\cimv2", "WQL", "SELECT * FROM Win32_LogicalDisk");
// Loop through all volumes
foreach (CimInstance oneVolume in allVolumes)
{
Console.Writeline(oneVolume.CimInstanceProperties["SystemName"].Value.ToString());
}
I am not sure what to take as paramaters for domain and username for a local computer. I have already done/tryed the following:
run winrm quickconfig on the remote local computer
use PasswordAuthenticationMechanism.Negotiate cause I have read Kerberos only
works for domain users and password
added the computer I run the code on to the TrustedHosts on the local computer with winrm config. Also tryed adding * to the TrustedHosts
Used for username="computer_B\LocalAdminUserName". I have also tryed with domain=""
Any suggestions what I am doing wrong?
The error I keep getting is: WinRM cannot process the request. The following error with error code 0x8009030e occurred while using Negotiate authentication: A specified logon session does not exist. It may already have been terminated.
This can occur if the provided credentials are not valid on the target server, or if the server identity could not be verified. If you trust the server identity, add the server name to the TrustedHosts list, and then retry the request. Use winrm.cmd to view or edit the TrustedHosts list. Note that computers in the TrustedHosts list might not be authenticated. For more information about how to edit the TrustedHosts list, run the following command: winrm help config.
Try out the code below, this is working on impersonation logic.
ConnectionOptions cOption = new ConnectionOptions();
ManagementScope scope = null;
Boolean isLocalConnection = isLocalhost(machine);
if (isLocalConnection)
{
scope = new ManagementScope(nameSpaceRoot + "\\" + managementScope, cOption);
}
else
{
scope = new ManagementScope("\\\\" + machine + "\\" + nameSpaceRoot + "\\" + managementScope, cOption);
}
if (!String.IsNullOrEmpty(ACTIVE_DIRECTORY_USERNAME) && !String.IsNullOrEmpty(ACTIVE_DIRECTORY_PASSWORD) && !isLocalConnection)
{
scope.Options.Username = ACTIVE_DIRECTORY_USERNAME;
scope.Options.Password = ACTIVE_DIRECTORY_PASSWORD;
}
scope.Options.EnablePrivileges = true;
scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
scope.Options.Impersonation = ImpersonationLevel.Impersonate;
scope.Connect();
I am trying to create an application that will programmatically login 10 users using RDP. The purpose is to autologin these users so someone does not have to manually do it. The first server I tested against (Server 2012) worked just fine. However, I tried a Server 2008 R2 and it continues to prompt me for a password. Here is the code.
static void Main(string[] args)
{
var password = ConfigurationManager.AppSettings["Password"];
var machine = ConfigurationManager.AppSettings["MachineName"];
var userNameList = new List<string>(ConfigurationManager.AppSettings["UserName"].Split(new char[] { ';' }));
foreach(string name in userNameList)
{
Process rdpProcess = new Process();
rdpProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\cmdkey.exe");
rdpProcess.StartInfo.Arguments = "/generic:TERMSRV/" + machine + "/user:" + name + " /pass:" + password;
rdpProcess.Start();
rdpProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\mstsc.exe");
rdpProcess.StartInfo.Arguments = "/v " + machine;
rdpProcess.Start();
Thread.Sleep(3000);
}
}
I added the sleep as the connections were coming too fast and I was getting "connection is busy" errors.
Can anyone see anything I am doing wrong?
Don't really know why this was the case but my 2008 servers will not work with FQDN. IP works fine though. Whatever..
I want to open process pon remote machine, this remote machine is inside local network.
I try this command and in the remote machine nothing happen, this user that i connect with have administrators rights.
Both machines running Windows 7
static void Main(string[] args)
{
try
{
//Assign the name of the process you want to kill on the remote machine
string processName = "notepad.exe";
//Assign the user name and password of the account to ConnectionOptions object
//which have administrative privilege on the remote machine.
ConnectionOptions connectoptions = new ConnectionOptions();
connectoptions.Username = #"MyDomain\MyUser";
connectoptions.Password = "12345678";
//IP Address of the remote machine
string ipAddress = "192.168.0.100";
ManagementScope scope = new ManagementScope(#"\\" + ipAddress + #"\root\cimv2", connectoptions);
//Define the WMI query to be executed on the remote machine
SelectQuery query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
object[] methodArgs = { "notepad.exe", null, null, 0 };
using (ManagementObjectSearcher searcher = new
ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject process in searcher.Get())
{
//process.InvokeMethod("Terminate", null);
process.InvokeMethod("Create", methodArgs);
}
}
Console.ReadLine();
}
catch (Exception ex)
{
//Log exception in exception log.
//Logger.WriteEntry(ex.StackTrace);
Console.WriteLine(ex.StackTrace);
}
}
you are not opening a process with that code but you are enumerating all the running process named "iexplore.exe" and close them.
I think an easier, better way is to use SysInternals PsExec or the Task Scheduler API
If you want to use WMI your code should look like this:
object theProcessToRun = { "YourFileHere" };
ManagementClass theClass = new ManagementClass(#"\\server\root\cimv2:Win32_Process");
theClass.InvokeMethod("Create", theProcessToRun);
----------In reply to your comment------------------
First of all you need to change your attitude and approach to coding and read the code that your are copy/pasting.
Then you should study a little more about programming languages.
No I will not write the code for you. I gave you an hint to point to the right direction. now it is your turn to develop it. Have fun!!
This is script that i did for my company before this using vbs script. can search the net to convert it to C# or etc. Fundamental of the steps and how to start a service using WMI. Have a nice coding and have fun.
sUser = "TESTDomain\T-CL-S"
sPass = "Temp1234"
Set ServiceSet = GetObject("winmgmts:").ExecQuery("Select * from Win32_Service where Name = 'netlogon'")
For Each Service In ServiceSet
Service.StopService
Service.Change "netlogon",Service.PathName, , ,"Automatic",false,sUser,sPass
Service.StartService
Next
Set Service = Nothing
Set ServiceSet = Nothing