本文整理汇总了C#中System.Management.Automation.PSCredential.GetNetworkCredential方法的典型用法代码示例。如果您正苦于以下问题:C# PSCredential.GetNetworkCredential方法的具体用法?C# PSCredential.GetNetworkCredential怎么用?C# PSCredential.GetNetworkCredential使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Management.Automation.PSCredential
的用法示例。
在下文中一共展示了PSCredential.GetNetworkCredential方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PowerShellProcessInstance
public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
{
this._syncObject = new object();
string pSExePath = PSExePath;
if (useWow64)
{
string environmentVariable = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
if (!string.IsNullOrEmpty(environmentVariable) && (environmentVariable.Equals("amd64", StringComparison.OrdinalIgnoreCase) || environmentVariable.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
{
pSExePath = PSExePath.ToLowerInvariant().Replace(@"\system32\", @"\syswow64\");
if (!System.IO.File.Exists(pSExePath))
{
throw new PSInvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.IPCWowComponentNotPresent, new object[] { pSExePath }));
}
}
}
string str4 = string.Empty;
Version version = powerShellVersion ?? PSVersionInfo.PSVersion;
if (null == version)
{
version = new Version(3, 0);
}
str4 = string.Format(CultureInfo.InvariantCulture, "-Version {0}", new object[] { new Version(version.Major, version.Minor) });
str4 = string.Format(CultureInfo.InvariantCulture, "{0} -s -NoLogo -NoProfile", new object[] { str4 });
if (initializationScript != null)
{
string str5 = initializationScript.ToString();
if (!string.IsNullOrEmpty(str5))
{
string str6 = Convert.ToBase64String(Encoding.Unicode.GetBytes(str5));
str4 = string.Format(CultureInfo.InvariantCulture, "{0} -EncodedCommand {1}", new object[] { str4, str6 });
}
}
ProcessStartInfo info = new ProcessStartInfo {
FileName = useWow64 ? pSExePath : PSExePath,
Arguments = str4,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
LoadUserProfile = true
};
this._startInfo = info;
if (credential != null)
{
NetworkCredential networkCredential = credential.GetNetworkCredential();
this._startInfo.UserName = networkCredential.UserName;
this._startInfo.Domain = string.IsNullOrEmpty(networkCredential.Domain) ? "." : networkCredential.Domain;
this._startInfo.Password = credential.Password;
}
System.Diagnostics.Process process = new System.Diagnostics.Process {
StartInfo = this._startInfo,
EnableRaisingEvents = true
};
this._process = process;
}
示例2: InstantiateSPOSiteContext
internal static SPOSiteContext InstantiateSPOSiteContext(Uri url, PSCredential credentials, PSHost host, bool isNetworkCredentials)
{
if (!IsValidServerVersion(url))
{
throw new InvalidOperationException("Could not connect to SharePoint Online: unsupported version of service.");
}
CmdletContext context = new CmdletContext(url.AbsoluteUri, host);
if (isNetworkCredentials)
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = credentials.GetNetworkCredential();
}
else
{
context.Credentials = new SharePointOnlineCredentials(credentials.UserName, credentials.Password);
}
if (context.HasPendingRequest)
context.ExecuteQuery();
return new SPOSiteContext(context);
}
示例3: InstantiateAdfsConnection
internal static SPOnlineConnection InstantiateAdfsConnection(Uri url, PSCredential credentials, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
{
Core.AuthenticationManager authManager = new Core.AuthenticationManager();
var networkCredentials = credentials.GetNetworkCredential();
string adfsHost;
string adfsRelyingParty;
GetAdfsConfigurationFromTargetUri(url, out adfsHost, out adfsRelyingParty);
if (string.IsNullOrEmpty(adfsHost) || string.IsNullOrEmpty(adfsRelyingParty))
{
throw new Exception("Cannot retrieve ADFS settings.");
}
var context = PnPClientContext.ConvertFrom(authManager.GetADFSUserNameMixedAuthenticatedContext(url.ToString(), networkCredentials.UserName, networkCredentials.Password, networkCredentials.Domain, adfsHost, adfsRelyingParty), retryCount, retryWait * 1000);
context.RetryCount = retryCount;
context.Delay = retryWait * 1000;
context.ApplicationName = Properties.Resources.ApplicationName;
context.RequestTimeout = requestTimeout;
var connectionType = ConnectionType.OnPrem;
if (skipAdminCheck == false)
{
if (IsTenantAdminSite(context))
{
connectionType = ConnectionType.TenantAdmin;
}
}
return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString());
}
示例4: GetCredConnectionInfo
/// <summary>
///
/// </summary>
/// <param name="computer"></param>
/// <param name="port"></param>
/// <param name="credential"></param>
/// <param name="proxyserver"></param>
/// <param name="proxytype"></param>
/// <param name="proxyport"></param>
/// <param name="proxycredential"></param>
/// <param name="kIconnectInfo"></param>
/// <returns></returns>
public static ConnectionInfo GetCredConnectionInfo(string computer,
int port,
PSCredential credential,
string proxyserver,
string proxytype,
int proxyport,
PSCredential proxycredential,
KeyboardInteractiveAuthenticationMethod kIconnectInfo)
{
ConnectionInfo connectionInfo;
var passconnectInfo = new PasswordAuthenticationMethod(credential.UserName,
credential.GetNetworkCredential().Password);
if (proxyserver != String.Empty)
{
// Set the proper proxy type
var ptype = ProxyTypes.Http;
switch (proxytype)
{
case "HTTP":
ptype = ProxyTypes.Http;
break;
case "Socks4":
ptype = ProxyTypes.Socks4;
break;
case "Socks5":
ptype = ProxyTypes.Socks5;
break;
}
if (proxycredential.UserName != String.Empty)
{
connectionInfo = new ConnectionInfo(computer,
port,
credential.UserName,
ptype,
proxyserver,
proxyport,
String.Empty,
String.Empty,
kIconnectInfo,
passconnectInfo);
}
else
{
connectionInfo = new ConnectionInfo(computer,
port,
credential.UserName,
ptype,
proxyserver,
proxyport,
proxycredential.UserName,
proxycredential.GetNetworkCredential().Password,
kIconnectInfo,
passconnectInfo);
}
}
else // Handle connection with no proxy server
{
connectionInfo = new ConnectionInfo(computer,
port,
credential.UserName,
passconnectInfo,
kIconnectInfo);
}
return connectionInfo;
}
示例5: GetKeyConnectionInfo
private static PrivateKeyConnectionInfo GetKeyConnectionInfo(string computer,
int port,
Stream keyFileStream,
PSCredential credential,
string proxyserver,
string proxytype,
int proxyport,
PSCredential proxycredential)
{
PrivateKeyConnectionInfo connectionInfo;
// Create the key object.
PrivateKeyFile sshkey;
if (credential.GetNetworkCredential().Password == String.Empty)
sshkey = new PrivateKeyFile(keyFileStream);
else
sshkey = new PrivateKeyFile(keyFileStream, credential.GetNetworkCredential().Password);
if (proxyserver != String.Empty)
{
// Set the proper proxy type
var ptype = ProxyTypes.Http;
switch (proxytype)
{
case "HTTP":
ptype = ProxyTypes.Http;
break;
case "Socks4":
ptype = ProxyTypes.Socks4;
break;
case "Socks5":
ptype = ProxyTypes.Socks5;
break;
}
if (proxycredential.UserName != String.Empty)
{
connectionInfo = new PrivateKeyConnectionInfo(computer,
port,
credential.UserName,
ptype,
proxyserver,
proxyport,
sshkey);
}
else
{
connectionInfo = new PrivateKeyConnectionInfo(computer,
port,
credential.UserName,
ptype,
proxyserver,
proxyport,
proxycredential.UserName,
proxycredential.GetNetworkCredential().Password,
sshkey);
}
}
else // Handle connection with no proxy server
{
connectionInfo = new PrivateKeyConnectionInfo(computer,
port,
credential.UserName,
sshkey);
}
return connectionInfo;
}
示例6: CreateCimCredentials
/// <summary>
/// Create credentials based on given authentication type and PSCredential
/// </summary>
/// <param name="psCredentials"></param>
/// <param name="passwordAuthentication"></param>
/// <returns></returns>
internal CimCredential CreateCimCredentials(PSCredential psCredentials,
PasswordAuthenticationMechanism passwordAuthentication,
string operationName,
string parameterName)
{
DebugHelper.WriteLogEx("PSCredential:{0}; PasswordAuthenticationMechanism:{1}; operationName:{2}; parameterName:{3}.", 0, psCredentials, passwordAuthentication, operationName, parameterName);
CimCredential credentials = null;
if (psCredentials != null)
{
NetworkCredential networkCredential = psCredentials.GetNetworkCredential();
DebugHelper.WriteLog("Domain:{0}; UserName:{1}; Password:{2}.", 1, networkCredential.Domain, networkCredential.UserName, psCredentials.Password);
credentials = new CimCredential(passwordAuthentication, networkCredential.Domain, networkCredential.UserName, psCredentials.Password);
}
else
{
ImpersonatedAuthenticationMechanism impersonatedAuthentication;
switch (passwordAuthentication)
{
case PasswordAuthenticationMechanism.Default:
impersonatedAuthentication = ImpersonatedAuthenticationMechanism.None;
break;
case PasswordAuthenticationMechanism.Negotiate:
impersonatedAuthentication = ImpersonatedAuthenticationMechanism.Negotiate;
break;
case PasswordAuthenticationMechanism.Kerberos:
impersonatedAuthentication = ImpersonatedAuthenticationMechanism.Kerberos;
break;
case PasswordAuthenticationMechanism.NtlmDomain:
impersonatedAuthentication = ImpersonatedAuthenticationMechanism.NtlmDomain;
break;
default:
ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication);
return null;
}
credentials = new CimCredential(impersonatedAuthentication);
}
DebugHelper.WriteLogEx("return credential {0}", 1, credentials);
return credentials;
}
示例7: CreateSessionObject
internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string connectionString, string certificateThumbprint, bool usessl)
{
WSManHelper.ValidateSpecifiedAuthentication(authentication, credential, certificateThumbprint);
int num = 0;
if (authentication.ToString() != null)
{
if (authentication.Equals(AuthenticationMechanism.None))
{
num = num | 0x8000;
}
if (authentication.Equals(AuthenticationMechanism.Basic))
{
num = num | 0x40000 | 0x1000;
}
if (authentication.Equals(AuthenticationMechanism.Negotiate))
{
num = num | 0x20000;
}
if (authentication.Equals(AuthenticationMechanism.Kerberos))
{
num = num | 0x80000;
}
if (authentication.Equals(AuthenticationMechanism.Digest))
{
num = num | 0x10000 | 0x1000;
}
if (authentication.Equals(AuthenticationMechanism.Credssp))
{
num = num | 0x1000000 | 0x1000;
}
if (authentication.Equals(AuthenticationMechanism.ClientCertificate))
{
num = num | 0x200000;
}
}
IWSManConnectionOptionsEx2 userName = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions();
if (credential != null)
{
if (credential.UserName != null)
{
NetworkCredential networkCredential = credential.GetNetworkCredential();
if (!string.IsNullOrEmpty(networkCredential.Domain))
{
userName.UserName = string.Concat(networkCredential.Domain, "\\", networkCredential.UserName);
}
else
{
if (authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic))
{
userName.UserName = networkCredential.UserName;
}
else
{
userName.UserName = string.Concat("\\", networkCredential.UserName);
}
}
userName.Password = networkCredential.Password;
if (!authentication.Equals(AuthenticationMechanism.Credssp) || !authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic))
{
num = num | 0x1000;
}
}
}
if (certificateThumbprint != null)
{
userName.CertificateThumbprint = certificateThumbprint;
num = num | 0x200000;
}
if (sessionoption == null)
{
num = num | 1;
}
else
{
if (sessionoption.ProxyAuthentication != 0)
{
int num1 = 0;
int num2 = 0;
if (!sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyIEConfig))
{
if (!sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyAutoDetect))
{
if (!sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyNoProxyServer))
{
if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyWinHttpConfig))
{
num1 = userName.ProxyWinHttpConfig();
}
}
else
{
num1 = userName.ProxyNoProxyServer();
}
}
else
{
num1 = userName.ProxyAutoDetect();
}
}
else
//.........这里部分代码省略.........
示例8: LogOnUser
/// <summary>
/// Logs on the user.
/// </summary>
/// <param name="credential">The credential.</param>
/// <returns>The LogOnUser object.</returns>
private LogOnUser LogOnUser(PSCredential credential)
{
LogOnUser logOnUser = null;
if (this.ImpersonatePowerShellUser)
{
LogOnType logonType = this.ImpersonatePowerShellUserLogOnType;
bool loadUserProfile = this.ImpersonatePowerShellUserLoadUserProfile;
WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
if (windowsIdentity != null)
{
string currentUserLogonName = windowsIdentity.Name;
if (!this.PowerShellUser.Equals(currentUserLogonName, StringComparison.OrdinalIgnoreCase))
{
logOnUser = new LogOnUser(
credential.GetNetworkCredential().UserName,
credential.GetNetworkCredential().Domain,
credential.GetNetworkCredential().Password,
logonType,
LogOnProvider.ProviderWinNT50,
loadUserProfile);
}
}
else
{
logOnUser = new LogOnUser(
credential.GetNetworkCredential().Domain,
credential.GetNetworkCredential().UserName,
credential.GetNetworkCredential().Password,
logonType,
LogOnProvider.ProviderWinNT50,
loadUserProfile);
}
}
return logOnUser;
}
示例9: SetUpDefaultRemoteAppCollectionSet
public static int SetUpDefaultRemoteAppCollectionSet(Mock<IRemoteAppManagementClient> clientMock,string collectionName, string subscriptionId, string billingPlan, string imageName, PSCredential credential, string domainName, string trackingId)
{
NetworkCredential cred = credential != null ? credential.GetNetworkCredential() : null;
CollectionCreationDetails collectionDetails = new CollectionCreationDetails()
{
Name = collectionName,
PlanName = billingPlan,
TemplateImageName = imageName,
Mode = CollectionMode.Apps,
Description = "unit test"
};
if (cred != null)
{
collectionDetails.AdInfo = new ActiveDirectoryConfig()
{
DomainName = domainName,
UserName = cred.UserName,
Password = cred.Password
};
}
List<Collection> collectionList = new List<Collection>()
{
new Collection()
{
Name = collectionDetails.Name,
PlanName = collectionDetails.PlanName,
TemplateImageName = collectionDetails.TemplateImageName,
Mode = collectionDetails.Mode,
Description = collectionDetails.Description,
Status = "Active",
AdInfo = collectionDetails.AdInfo != null ? collectionDetails.AdInfo : null
}
};
OperationResultWithTrackingId response = new OperationResultWithTrackingId()
{
StatusCode = System.Net.HttpStatusCode.Accepted,
TrackingId = trackingId,
RequestId = "222-3456-789"
};
mockTrackingId = new List<TrackingResult>()
{
new TrackingResult(response)
};
ISetup<IRemoteAppManagementClient, Task<OperationResultWithTrackingId>> setup =
clientMock.Setup(
c => c.Collections.SetAsync(
collectionName,
It.IsAny<bool>(),
It.IsAny<bool>(),
It.IsAny<CollectionUpdateDetails>(),
It.IsAny<CancellationToken>()));
setup.Returns(Task.Factory.StartNew(() => response));
mockCollectionList = collectionList;
return mockCollectionList.Count;
}
示例10: CreateSessionObject
internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string connectionString, string certificateThumbprint, bool usessl)
{
ValidateSpecifiedAuthentication(authentication, credential, certificateThumbprint);
////if authentication is given
int sessionFlags = 0;
if (authentication.ToString() != null)
{
if (authentication.Equals(AuthenticationMechanism.None))
{
sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseNoAuthentication;
}
if (authentication.Equals(AuthenticationMechanism.Basic))
{
sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseBasic | (int)WSManSessionFlags.WSManFlagCredUserNamePassword;
}
if (authentication.Equals(AuthenticationMechanism.Negotiate))
{
sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseNegotiate;
}
if (authentication.Equals(AuthenticationMechanism.Kerberos))
{
sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseKerberos;
}
if (authentication.Equals(AuthenticationMechanism.Digest))
{
sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseDigest | (int)WSManSessionFlags.WSManFlagCredUserNamePassword;
}
if (authentication.Equals(AuthenticationMechanism.Credssp))
{
sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseCredSsp | (int)WSManSessionFlags.WSManFlagCredUserNamePassword;
}
if (authentication.Equals(AuthenticationMechanism.ClientCertificate))
{
sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate;
}
}
IWSManConnectionOptionsEx2 connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions();
if (credential != null)
{
//connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions();
System.Net.NetworkCredential nwCredential = new System.Net.NetworkCredential();
if (credential.UserName != null)
{
nwCredential = credential.GetNetworkCredential();
if (String.IsNullOrEmpty(nwCredential.Domain))
{
if ( authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic) )
{
connObject.UserName = nwCredential.UserName;
}
else
{
// just wanted to not use null domain, empty is actually fine
connObject.UserName = "\\" + nwCredential.UserName;
}
}
else
{
connObject.UserName = nwCredential.Domain + "\\" + nwCredential.UserName;
}
connObject.Password = nwCredential.Password;
if (!authentication.Equals(AuthenticationMechanism.Credssp) || !authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic))
{
sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagCredUserNamePassword;
}
}
}
if (certificateThumbprint != null)
{
connObject.CertificateThumbprint = certificateThumbprint;
sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate;
}
if (sessionoption != null)
{
if (sessionoption.ProxyAuthentication != 0)
{
int ProxyAccessflags = 0;
int ProxyAuthenticationFlags = 0;
if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyIEConfig))
{
ProxyAccessflags = connObject.ProxyIEConfig();
}
else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyAutoDetect))
{
ProxyAccessflags = connObject.ProxyAutoDetect();
}
else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyNoProxyServer))
{
ProxyAccessflags = connObject.ProxyNoProxyServer();
}
else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyWinHttpConfig))
{
ProxyAccessflags = connObject.ProxyWinHttpConfig();
//.........这里部分代码省略.........
示例11: CreateCimCredentials
internal CimCredential CreateCimCredentials(PSCredential psCredentials, PasswordAuthenticationMechanism passwordAuthentication, string operationName, string parameterName)
{
CimCredential cimCredential;
ImpersonatedAuthenticationMechanism impersonatedAuthenticationMechanism;
object[] objArray = new object[4];
objArray[0] = psCredentials;
objArray[1] = passwordAuthentication;
objArray[2] = operationName;
objArray[3] = parameterName;
DebugHelper.WriteLogEx("PSCredential:{0}; PasswordAuthenticationMechanism:{1}; operationName:{2}; parameterName:{3}.", 0, objArray);
if (psCredentials == null)
{
PasswordAuthenticationMechanism passwordAuthenticationMechanism = passwordAuthentication;
if (passwordAuthenticationMechanism == PasswordAuthenticationMechanism.Default)
{
impersonatedAuthenticationMechanism = ImpersonatedAuthenticationMechanism.None;
}
else if (passwordAuthenticationMechanism == PasswordAuthenticationMechanism.Digest || passwordAuthenticationMechanism == PasswordAuthenticationMechanism.Basic)
{
this.ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication);
return null;
}
else if (passwordAuthenticationMechanism == PasswordAuthenticationMechanism.Negotiate)
{
impersonatedAuthenticationMechanism = ImpersonatedAuthenticationMechanism.Negotiate;
}
else if (passwordAuthenticationMechanism == PasswordAuthenticationMechanism.Kerberos)
{
impersonatedAuthenticationMechanism = ImpersonatedAuthenticationMechanism.Kerberos;
}
else if (passwordAuthenticationMechanism == PasswordAuthenticationMechanism.NtlmDomain)
{
impersonatedAuthenticationMechanism = ImpersonatedAuthenticationMechanism.NtlmDomain;
}
else
{
this.ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication);
return null;
}
cimCredential = new CimCredential(impersonatedAuthenticationMechanism);
}
else
{
NetworkCredential networkCredential = psCredentials.GetNetworkCredential();
/* Send directly PSCredentials SecurePassword if NetworkCredentials password is only encrypted */
object[] domain = new object[3];
domain[0] = networkCredential.Domain;
domain[1] = networkCredential.UserName;
domain[2] = networkCredential.SecurePassword ?? psCredentials.Password;
DebugHelper.WriteLog("Domain:{0}; UserName:{1}; Password:{2}.", 1, domain);
cimCredential = new CimCredential(passwordAuthentication, networkCredential.Domain, networkCredential.UserName, networkCredential.SecurePassword ?? psCredentials.Password);
}
object[] objArray1 = new object[1];
objArray1[0] = cimCredential;
DebugHelper.WriteLogEx("return credential {0}", 1, objArray1);
return cimCredential;
this.ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication);
return null;
}
示例12: GetKeyConnectionInfo
/// <summary>
/// Generate a ConnectionInfoObject using a SSH Key.
/// </summary>
/// <param name="computer"></param>
/// <param name="port"></param>
/// <param name="keyfile"></param>
/// <param name="credential"></param>
/// <param name="proxyserver"></param>
/// <param name="proxytype"></param>
/// <param name="proxyport"></param>
/// <param name="proxycredential"></param>
/// <returns></returns>
public static PrivateKeyConnectionInfo GetKeyConnectionInfo(string computer,
int port,
string keyfile,
PSCredential credential,
string proxyserver,
string proxytype,
int proxyport,
PSCredential proxycredential)
{
PrivateKeyConnectionInfo connectionInfo;
var fullPath = Path.GetFullPath(keyfile);
// Check if the file actually exists.
if (File.Exists(fullPath))
{
// Create the key object.
PrivateKeyFile sshkey;
if (credential.GetNetworkCredential().Password == "")
{
sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
}
else
{
sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);
}
if (proxyserver != "")
{
// Set the proper proxy type
var ptype = ProxyTypes.Http;
switch (proxytype)
{
case "HTTP":
ptype = ProxyTypes.Http;
break;
case "Socks4":
ptype = ProxyTypes.Socks4;
break;
case "Socks5":
ptype = ProxyTypes.Socks5;
break;
}
if (proxycredential.UserName != "")
{
connectionInfo = new PrivateKeyConnectionInfo(computer,
port,
credential.UserName,
ptype,
proxyserver,
proxyport,
sshkey);
}
else
{
connectionInfo = new PrivateKeyConnectionInfo(computer,
port,
credential.UserName,
ptype,
proxyserver,
proxyport,
proxycredential.UserName,
proxycredential.GetNetworkCredential().Password,
sshkey);
}
}
else // Handle connection with no proxy server
{
connectionInfo = new PrivateKeyConnectionInfo(computer,
port,
credential.UserName,
sshkey);
}
} // file exists
else
{
throw new FileNotFoundException("Key file " + fullPath + " was not found.");
}
return connectionInfo;
}
示例13: NewClient
private static PrivateClient NewClient(string uri, PSCredential credential)
{
CustomBinding custBinding = new CustomBinding();
MtomMessageEncodingBindingElement elmtom = new MtomMessageEncodingBindingElement();
elmtom.MaxWritePoolSize = 2147483647;
elmtom.MaxBufferSize = 2147483647;
elmtom.MessageVersion = MessageVersion.Soap12;
var ssbe = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
ssbe.AllowInsecureTransport = true;
ssbe.IncludeTimestamp = false;
ssbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
var htt = new HttpTransportBindingElement();
htt.MaxBufferPoolSize = 2147483647;
htt.MaxReceivedMessageSize = 2147483647;
htt.MaxBufferSize = 2147483647;
EndpointAddress n = new EndpointAddress(uri);
custBinding.Elements.Add(ssbe);
custBinding.Elements.Add(elmtom);
custBinding.Elements.Add(htt);
var client = new PrivateClient(custBinding, n);
if (credential != null)
{
if (client.ClientCredentials != null)
{
client.ClientCredentials.UserName.UserName = credential.GetNetworkCredential().UserName;
client.ClientCredentials.UserName.Password = SecureStringToString(credential.Password);
}
}
else
{
if (client.ClientCredentials != null)
{
// client.ClientCredentials.UserName.UserName = "admin";
//client.ClientCredentials.UserName.Password = "admin";
}
}
return client;
}